The Sysadmin Notebook  

Sitemap

Error Handling

Catching and Handling Errors in Javascript

Contents

Try Catch Finally

Top Bottom

Javascript provides a try-catch-finally control structure to handle runtime and throw errors. When an error is thrown, the javascript interpretor searches within the current block for a try-catch-finally structure to handle the error. If none is found, the enclosing block is searched, and so on until an error handler is found.

The 'try { }' statement can be used to enclose a block of code. If an error occurs within the block, then the javascript interpreter searches for a 'catch (err) { }' block, and passes execution to this block to handle the error. A 'finally { }' block can also be included to provide some default actions. If a 'finally' block exists, then this will always be executed, whether or not an error occurs. The 'catch' block only executes if an error occurs.

try {
	statement
}
catch (e) {
	statement
}
finally {
	statement
}

A try block must be followed by at least one 'catch' or 'finally' block.

Throw

Top Bottom

The 'throw' statement allows you to generate a exception that signals the javascript interpreter that an error has occurred. Normally, throw is used with an expression that generates an object of class Error:

if (isNaN(x))
    throw new Error(typeof(x) + 
    "provided where number expected\n" + 
    "Value: " + x);
alert("No error");