Skip to main content

avoid-throw-in-catch-block

Warns when a throw expression is called inside a catch block

Calling throw inside a catch block loses the original stack trace and the original exception.

Since Dart 2.16 you can use Error.throwWithStackTrace to avoid loosing the original stack trace.

Example

❌ Bad:

void repository() {
try {
networkDataProvider();
} on Object {
// LINT: Avoid 'throw' inside a catch block as it causes the original stack trace and the original exception to be lost.
// Try using 'rethrow or 'Error.throwWithStackTrace'.
throw RepositoryException();
}
}

✅ Good:

void repository() {
try {
networkDataProvider();
} catch (_, stack) {
Error.throwWithStackTrace(RepositoryException(), stack);
}
}