Skip to content

dart:async - runZoned defeats expected try-catch-finally behaviour #47476

@JohnColeman-CTO

Description

@JohnColeman-CTO

Output from the code below is:

Got 0
Got 1
Got 2
Got 3
Got 4
Got 5
Got 6
Got 7
Got 8
Got 9
handled error: 9
Unhandled exception:
error: 9
#0      example (file:///Users/johncoleman/WebstormProjects/zones_events_micro_dart_tutorial/bin/main.dart:23:17)
<asynchronous suspension>
#1      main.<anonymous closure> (file:///Users/johncoleman/WebstormProjects/zones_events_micro_dart_tutorial/bin/main.dart:6:7)
<asynchronous suspension>
#2      main (file:///Users/johncoleman/WebstormProjects/zones_events_micro_dart_tutorial/bin/main.dart:5:5)
<asynchronous suspension>

Process finished with exit code 255

The printing of "handled error: 9" executes as expect but 2 other prints are never executed contrary to the normal understanding of try-catch-finally behaviour with respect to the code that is wrapped.

import 'dart:async';

main() async {
  try {
    await runZoned(() async {
      await example();
    }, onError: (error, stacktrace) {
      print('handled $error');
      throw error;
    });
  } catch (error) {
    print("caught $error"); // this does not print
  } finally {
    print("finally done"); // this does not print
  }
}

Future example() async {
  await for (var x in streamer()) {
    print('Got $x');
    if (x == 9) throw ('error: $x');
  }
}

Stream<int> streamer() async* {
  var duration = Duration(milliseconds: 100);
  for (var x = 0; x < 100; x++) {
    await Future.delayed(duration);
    yield x;
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions