Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading