Home > Enterprise >  Dart: Why is an async error not caught when it is thrown in the constructor body?
Dart: Why is an async error not caught when it is thrown in the constructor body?

Time:06-02

main() async {
  try {
    final t = Test();
    await Future.delayed(Duration(seconds: 1));
  } catch (e) {
    // Never printed
    print("caught");
  }
}

void willThrow() async {
  throw "error";
}

class Test {
  Test() {
    willThrow();
  }
}

If the "async" keyword is removed from willThrow everything works as expected.

Is it because you can't await a constructor? If so is there anyway to catch async errors in a constructor body?

CodePudding user response:

Have this a go:

void main() async {
  try {
    final t = Test();
    await Future.delayed(Duration(seconds: 1));
  } catch (e) {
    // Never printed
    print("caught");
  }
}

Future<void> willThrow() async {
  throw "error";
}

class Test {
  Test() {
    willThrow().catchError((e){print('Error is caught here with msg: $e');});
  }
}

As to the 'why':

You use a normal try/catch to catch the failures of awaited asynchronous computations. But since you cannot await the constructor, you have to register the callback that handles the exception in another way. I think :)

  • Related