2

Im coming from a Java background where I use the throws keyword to lead an exception to the method calling another method. How can I do that I dart?

Method called:

  void _updateCurrentUserEmail() async {
    await FirebaseAuth.instance
        .currentUser()
        .then((FirebaseUser user) {
      _email = user.email;
    });
  }

How it is called:

try {
  _updateCurrentUserEmail();
} on Exception {
  return errorScreen("No User Signed In!", barActions);
}

But it seems like the Exception is not caught, because I still get a NoSuchMethodException and the errorScreen is not shown.

Patrick
  • 552
  • 5
  • 17

4 Answers4

2

While you correctly used try/catch, the exception is coming from an async function that you did not await.

try/catch only catch exceptions thrown within that block. But since you wrote:

try {
  doSomethingAsyncThatWillTrowLater();
} catch (e) {

}

Then the exception thrown by the async method is thrown outside of the body of try (as try finished before the async function did), and therefore not caught.

Your solution is to either use await:

try {
  await doSomethingAsyncThatWillTrowLater();
} catch (e) {

}

Or use Future.catchError/Future.then:

doSomethingAsyncThatWillTrowLater().catchError((error) {
  print('Error: $error');
});
Rémi Rousselet
  • 256,336
  • 79
  • 519
  • 432
  • The second option would be great, but I can't do method().catchError... – Patrick Dec 25 '19 at 18:29
  • Sorry, but I have another question.I am calling the method in the build method. If I am using the second option, the changes would be made after the return statement, which leads to the same result. But I can't use the second option, because I can't make the build method async. – Patrick Dec 26 '19 at 19:12
0

Change it to this:

try {
  _updateCurrentUserEmail();
} on Exception catch(e){
    print('error caught: $e')
}

Another way to handle error is to do the following:

void _updateCurrentUserEmail() async {
    await FirebaseAuth.instance
        .currentUser()
        .then((FirebaseUser user) {
      _email = user.email;
      throw("some arbitrary error");
    });
   .catchError(handleError);
  }

handleError(e) {
    print('Error: ${e.toString()}');
  }

If currentUser()’s Future completes with a value, then()’s callback fires. If code within then()’s callback throws (as it does in the example above), then()’s Future completes with an error. That error is handled by catchError().

Check the docs:

https://dart.dev/guides/libraries/futures-error-handling

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
0

From the docs,

If the catch clause does not specify a type, that clause can handle any type of thrown object:

try {
  breedMoreLlamas();
} on OutOfLlamasException {
  // A specific exception
  buyMoreLlamas();
} on Exception catch (e) {
  // Anything else that is an exception
  print('Unknown exception: $e');   <------------------
} catch (e) {
  // No specified type, handles all
  print('Something really unknown: $e');
}
Ravinder Kumar
  • 7,407
  • 3
  • 28
  • 54
0

Throw

Here’s an example of throwing, or raising, an exception:

throw FormatException('Expected at least 1 section');

You can also throw arbitrary objects:

throw 'Out of llamas!';

throwing an exception is an expression, you can throw exceptions in => statements, as well as anywhere else that allows expressions:

void someMethod(Point other) => throw UnimplementedError();

here is example

main() { 
   try { 
      test_age(-2); 
   } 
   catch(e) { 
      print('Age cannot be negative'); 
   } 
}  
void test_age(int age) { 
   if(age<0) { 
      throw new FormatException(); 
   } 
}

hope it helps..

Jaydeep chatrola
  • 2,423
  • 11
  • 17