0

Why first case prints : "second level catch" "top level catch"

and second case prints: only "second level catch"?

Difference in finally block.


Future<void> main() async {
  try {
    secondLevelTryCatch();
  } catch (e, s) {
    print("top level catch");
  } 
}

void secondLevelTryCatch() {
  try {
    throw Exception();
  } catch (e, s) {
    print("second level catch");
    rethrow;
  } finally {
 //1 no return
 //2 return;
  }
//3return;
}


why 3 case print: "second level catch" "top level catch"

Андрей
  • 166
  • 2
  • 7
  • A `finally` block always runs after `try` and `catch`, so a `return` statement there wins. Using `return` in a `finally` block is almost always a bad idea. – jamesdlin Nov 20 '21 at 19:59
  • 1
    Additionally, there is an existing lint that warns you about using `return` in a `finally` block: https://dart-lang.github.io/linter/lints/control_flow_in_finally.html – jamesdlin Nov 20 '21 at 20:05
  • @jamesdlin but logic of rethrow to provide Exception on top level try catch. Why rethrow depends on finally return? If we return out finally (3 case) rethrow works. – Андрей Nov 21 '21 at 06:21
  • You explicitly told it to `return` from the `finally` block, so that's what it does. You specify two conflicting exit paths (throwing an exception and returning normally). Dart has to pick one, and the choice is mostly arbitrary. If Dart instead ignored the `return` statement, people probably would complain about that too. It also seems plausible to me that favoring the `finally` block might provide greater flexibility, but I haven't thought about it that much because you shouldn't write code like that anyway. – jamesdlin Nov 21 '21 at 06:54
  • Regarding your edited question: case 3 is not the same as case 2. A `finally` block is *guaranteed* to be executed after the `try` and any `catch` blocks. Code *after* a `try` block (and any associated `catch` and `finally` blocks) is *not* guaranteed to be executed. – jamesdlin Nov 21 '21 at 06:58

0 Answers0