0
votes

So I'm experimenting with a try/catch clause, and I don't understand why this is happening (normal or not):

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');
  }
}

So you see I'm trying to do a loop inside a loop, but on purpose, someList is not a List<List>, therefore the nested loop will throw an error ('inside' error) since 1 is an int, not a List.

That's the scenario, but what happens is it throws the 'outside' error.

Is this normal? If so, where did I go wrong?

1

1 Answers

1
votes

The exception you're getting is because w is undefined. If you change w to someList, then you'll get an exception for x not having an iterator, like you expect. You'll then handle that "inside" exception and immediately throw another one, which you'll catch, and then you'll throw the "outside" one, which you don't handle and will see an error for. (This might make it look like you're getting an "outside" error, but the error started on the "inside".)

This might make things clearer:

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