Handling Errors
JavaScript uses the try...catch statement to deal with errors.
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
<script type="text/javascript">
try {
var myArray;
for ( var i = 0; i < myArray.length; i++) {
document.writeln("Index " + i + ": " + myArray[i]);
}
} catch (e) {
document.writeln("Error: " + e);
}
</script>
</body>
</html>
The properties defined by the Error object:
| Property | Description | Returns |
|---|---|---|
| message | A description of the error condition. | string |
| name | The name of the error. This is Error, by default. | string |
| number | The error number, if any, for this kind of error. | number |
The optional finally clause is executed regardless of the error.
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
<script type="text/javascript">
try {
var myArray;
for ( var i = 0; i < myArray.length; i++) {
document.writeln("Index " + i + ": " + myArray[i]);
}
} catch (e) {
document.writeln("Error: " + e);
} finally {
document.writeln("Statements here are always executed");
}
</script>
</body>
</html>