JavaScript Statement: try … catch …
finally
[this page | pdf | back links]
In JavaScript,
the try … catch … finally statement (often used
in conjunction with the throw
statement) implements error handling. The statement takes e.g. the following
format:
try {
code1
}
catch(e) {
code2
}
finally {
code3
}
In the above, JavaScript
will first try to execute code1. If an error occurs, e.g. the code
cannot be understood or is misspelt and the (optional) catch statement is
present then instead of just stopping (which would be the usual response to an
error in the absence of a try
statement) it moves to code2. Regardless of the try / catch result, if
there is an (optional) finally
statement it will then execute code3. The type of error thrown (which
can be system specified or specified by the developer using the throw
statement is available through e, which is the name used in the code to
specify the local Error
object identifying the error.
Note: the catch and finally statement components are both optional, but you
typically need to include at least one of them when using a try statement.
Error objects have two
intrinsic properties, the .message
property which contains a description of the error and the .number property which contains the
error number of the error. Note, some browser suppliers
e.g. Microsoft have additional non-standard properties such as .description, which seems otherwise to
be the same as .message but will
not be recognised by non-Microsoft browsers (so should be avoided if users are
likely to use other browsers to view the relevant webpage).
Other modern
object-orientated programming languages such as Visual Basic also typically now
include structured error handling like the above, but potentially with
different forms of error object and with the error object potentially more
simply handling errors triggered within function calls.
EXAMPLE:
HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>
<script>
function crSp(n) { return '<br>' + (' ').repeat(n) }
var x = "";
var y = 1;
try { failprocess(y) }
catch(e) { x = e.description; }
finally {
if (x.length>0) {x = "Caught error is: " + x }
}
document.getElementById("Example").innerHTML =
'var x = "";'
+ crSp(0) + 'var y = 1;'
+ crSp(0) + 'try { failprocess(y) }'
+ crSp(0) + 'catch(e) { x = e.description; }'
+ crSp(0) + 'finally {'
+ crSp(2) + 'if (x.length>0) {x = "Caught error is: " + x }'
+ crSp(0) + '}';
document.getElementById("Result").innerHTML = x;
</script>
</body>
</html>
|
NAVIGATION LINKS
Contents | Prev | Next | JavaScript Reserved Words