Dart try / catch子句意外行为

时间:2013-06-29 08:22:53

标签: exception-handling try-catch dart

所以我正在尝试try / catch条款,我不明白为什么会发生这种情况(正常与否):

void main() {
  List someList = [1,2,3];
  try {
    for (var x in someList) {
      try {
        for (var z in x) {

        }
      } catch(e) {
        throw new Exception('inside');
      }
    }
  } catch(e) {
    throw new Exception('outside');
  }
}

所以你看我试图在循环中做一个循环,但是故意,someList不是List<List>,因此嵌套循环会抛出错误('inside'错误)由于1int,而不是List

这就是场景,但是会发生什么,它会引发“外部”错误。

这是正常的吗?如果是的话,我哪里出错?

1 个答案:

答案 0 :(得分:1)

您获得的异常是因为w未定义。如果您将w更改为someList,那么您将获得x没有迭代器的例外,就像您期望的那样。然后你将处理那个“内部”异常并立即抛出另一个异常,然后你将抛出一个你没有处理的“外部”异常,并且会看到错误。 (这可能会让你看起来像是一个“外部”错误,但错误始于“内部”。)

这可能会让事情变得更清楚:

void main() {
  List someList = [1,2,3];
  try {
    for (var x in someList) {
      try {
        for (var z in x) {             // This throws an exception

        }
      } catch(e) {                     // Which you catch here
        print(e);
        print("Throwing from inside");
        throw new Exception('inside'); // Now you throw another exception
      }
    }
  } catch(e) {                         // Which you catch here
    print(e);
    print("Throwing from outside");
    throw new Exception('outside');    // Now you throw a third exception
  }
}                                      // Which isn't caught, causing an
                                       //  "Unhandled exception" message
相关问题