Reputation:
I have an asynchronous method with a try catch block and it calls another async method that throws. My problem is that the thrown exception is not catched in the catch block.
Future savePlayer(Player player) async {
try {
var store = await SharedPreferences.getInstance();
await store.setString(_playerId, jsonEncode(player.toJson())); // exception in player.toJson() "NoSuchMethod"
} on Exception catch (err) {
throw LocalStorageException( // no catch here
message: TextConstants.exception.localStorageSaveException,
hint: TextConstants.exception.localStorageSaveExceptionHint,
originalExceptionText: err.toString());
} catch (err) {
throw LocalStorageException( // catch here, but why?
message: TextConstants.exception.localStorageSaveException,
hint: TextConstants.exception.localStorageSaveExceptionHint,
originalExceptionText: err.toString());
}
}
If I remove on Exception
and just use the catch
, then it works. This would be a valid workaround for me. But as I am using the Effective Dart coding rules I get a warning when omitting the on clause.
https://dart-lang.github.io/linter/lints/avoid_catches_without_on_clauses.html
What is the correct way to catch ANY exception in a catch block with an on
clause?
Upvotes: 0
Views: 295
Reputation: 89965
on Exception
catches objects of type Exception
.
What is being thrown is a NoSuchMethodError
, which is an Error
. Error
s are not Exception
s (nor vice-versa).
Dart distinguishes between runtime errors and logical errors (programmer errors). Runtime errors should derive from Exception
; logical errors should derive from Error
.
Effective Dart discourages catching Error
. They usually represent a programming mistake that could have and should have been avoided (e.g. calling a non-existent function).
Upvotes: 1