13. Exception handling #
Created Friday 11 March 2022
Why #
To handle exceptions and error, and provide a streamlined flow which segregates code functionality from the exceptional handling code.
How #
JavaScript has a 3 block structure for exception handling. There are 3 possible syntax constructs:
try
…catch
try
…finally
try
…catch
…finally
The role of blocks #
try
- has the functionality code which may lead to errors/exceptions/catch
- this block is executed when an exception is raised intry
. The block can optionally have an argument that takes the value of the raised exception.if
…else
(conditional) code may be used for more granular control of actions according to the type of exception raised, usinginstanceof
function. Example of conditonalcatch
block:try { myroutine(); // may throw three types of exceptions } catch (e) { if (e instanceof TypeError) { // statements to handle TypeError exceptions } else if (e instanceof RangeError) { // statements to handle RangeError exceptions } else if (e instanceof EvalError) { // statements to handle EvalError exceptions } else { // statements to handle any unspecified exceptions logMyErrors(e); // pass exception object to error handler } }
finally
- this block is always run, irrespective of whether an exception was raised or not.
Return value priority #
If something is returned from the block (s), the whole value evaluates is equal to return value from:
finally
- highest priority, even if thecatch
itself has more exceptions.catch
- If an exception was raised and there’s nofinally
(or it does not return anything).try
- if there are no exceptions, or ifcatch
/finally
return nothing, or are not defined.
Nesting of try blocks #
try
blocks may be nested inside each other.
- If a
try
block does not have acatch
but raises an error, then thecatch
of the enclosingtry
block handles the exception.
This is not used much, except in code that uses the async
-await
syntax.
Source: MDN