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
Catch and Catch (Exception e) have the same output, and the result is also the same if I write Throw or Throw e. Both are the same because you throw . @MarcGravell - Marc yes if he throws e there is a difference. Got it, I just wanted to re-tag but I see that has already been taken care of!
The try / on / catch Blocks The catch block is used when the handler needs the exception object. The try block must be followed by either exactly one on / catch block or one finally block (or one of both). When an exception occurs in the try block, the control is transferred to the catch.
When an exception is thrown in the try -block, exception_var (i.e., the e in catch (e) ) holds the exception value. You can use this identifier to get information about the exception that was thrown. This identifier is only available in the catch -block's scope.
Catch (Exception ex) catches all exceptions and in addition you can retrieve message through its reference. Use is dependent on requirement, if you want to show exception message you have facility to use ex. Message otherwise Catch (Exception) will be enough.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With