onPressed: () {
getName().then((value)
{
print(value);
print('YNWA');
throw('ERORRRRRR!');
}).catchError((error){
print('error is : ${error.toString()}');
});
},
and here is a method
Future<String> getName() async {
return 'Basel Elazaly';
}
}
why there is unhandled exception?
2
Answers
You haven’t specified what unhandled exception you’re getting. When I try it with:
the thrown
'ERORRRRRR!'
string is caught. However, the analyzer warns you that yourcatchError
block is incorrect because it doesn’t return the correct type, and that incorrectness results in a separate runtime error."What return type?" you might be wondering. Your
Future.then
callback’s body is:which unconditionally does
throw ('ERORRRRRR!')
. Therefore the return type of theFuture
is inferred to be aFuture<Never>
because that callback is statically determined to never returns normally. Therefore the return type of yourFuture.catchError
callback also must be of typeFuture<Never>
.If your callback body instead were:
then that would be sufficient to prevent static analysis from determining that the
throw
is always executed, the return type would be inferred asFuture<void>
instead, the return type of theFuture.catchError
callback would match, and you wouldn’t end up with an unhandled exception.The moral of the story (and of all stories that involve
Future.catchError
) is that you shouldn’t be usingFuture.catchError
at all. If you want to catch an error from aFuture
,await
thatFuture
with atry
block and usecatch
to handle whatever’s thrown.I think you’re facing occurs because throw(‘ERROR!’) throws a synchronous exception inside the then() block, but then() only catches asynchronous exceptions (exceptions thrown from Future-based operations).