Exception Handling
When errors can occur, it is good practice to handle them to either change the program or debug.
However, one may also wish to throw user-defined errors for specific cases and handle them in a try...catch.
- An example of this is when checking for, say, the boundaries of an object.
Error handling is all about this. Predicting and managing errors, or throwing your own errors for possibly bad data.
try...catch
The try...catch statement is powerful for handling errors; it makes code robust, safe and error-proof.
info
Throwing exceptions isn't always the best error-handling method.
A try...catch lets you execute things with access to the error, thereby resolving it.
A
try...catchstatement has atryblock, then acatchblock, and an optionalfinallyblock.The code in the
tryblock is executed first. If thetrythrows an exception or error:- Then the code in the
catch/finallyblock is executed.
- Then the code in the
Note that when there is a
finallyblock, it will always be executed.- It will execute before control flow exits the
try...catchconstruct.
- It will execute before control flow exits the
This is the syntax for try...catch blocks:
try {
tryStatements
} catch (exceptionVar) {
catchStatements
} [finally {
finallyStatements
}]
The
exceptionVaris an optional identifier to hold the caught exception.- If you don't need this, ignore it and write
catch { catchStatements }.
- If you don't need this, ignore it and write
An exception being thrown in the
tryblock immediately moves control flow tocatch.If
finallyis included, it will be executed no matter what.- A great example of
finallyis when trying to open a file, at the end no matter what close it
- A great example of
Let's see an example utilizing a try...catch with a finally too:
tip
A great use case of try...catch is to only catch (and silence) a small subset of expected errors, say RangeErrors.
As for other errors, just re-throw them if they're not relevant in your scenario.
For example: if (e instanceof RangeError) { //handle range error} else { throw e; }
The optional exception identifier can provide detailed information regarding the thrown Error/Exception.
Here's an example where the exception identifier isn't needed at all:
throw
The keyword throw is also used for exception handling, and using it throws a user-defined exception.
Similarly, control flow will be passed to the first catch block in the "stack".
- If there is no
catchblocks, the program simply terminates after throwing the error.
The different between throw and try...catch is:
throwis user-defined, so one can throw exceptions when atryblock wouldn'tAlso,
throwlets you throw objects and expressions
Here's an example of using throw:
tip
throw and try...catch can be combined. That is when exception handling is powerful.