Dart:为什么在构造函数体中抛出异步错误时没有捕获到它?

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

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

如果从 willThrow 中删除“async”关键字,一切都会按预期进行。

是因为不能等待构造函数吗?如果是这样的话,有没有办法在构造函数体中捕获异步错误?

试一试:

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

至于'why':

您使用正常的 try/catch 来捕获等待的异步计算的失败。但是由于您不能等待构造函数,因此您必须以另一种方式注册处理异常的回调。我认为:)