Difference between 'catch(e)' and 'on Exception catch(e)' in dart?

Viewed 2325

What is the difference between catch(e) and on Exception catch(e) in dart?

AVOID catches without on clauses.

Using catch clauses without on clauses makes your code prone to encountering unexpected errors that won't be thrown (and thus will go unnoticed).

BAD:

try {
 somethingRisky()
} catch(e) {
  doSomething(e);
}

GOOD:

try {
 somethingRisky()
} on Exception catch(e) {
  doSomething(e);
}

Link: avoid_catches_without_on_clauses

1 Answers

The } on Exception catch (e) { will catch all thrown objects implementing Exception. The excludes most errors (which implement Error),

The } catch (e) { will catch all thrown objects, both exceptions and errors - and anything else that might get thrown. Most thrown objects implement either Exception or Error, but that's just a convention. Any non-null object can be thrown.

I'd actually recommend against on Exception as well. Exceptions are not errors, they are intended for functions as an alternative to returning a value, but exceptions are still just as much part of the function API, and you should only be catching the exceptions that you are actually planning to handle. Since Exception itself has no information, you should be catching the subtype that the function is documented as throwing so you can use the available information to handle the exceptional case. If you are not going to handle it, you might as well treat the exception as an error.

Using only } catch (e) { to catch everything is reasonable in some situations, mainly in framework code which wraps other user code, and needs to make sure a user code error or unhandled exception doesn't take down the entire program.

Related