Like most programming languages, JavaScript provides a way to handle an exception that occurs in a block of code. This is done with the try/catch/finally statement. This statement works by defining a block of code to be run. This code is placement in the “try” portion of the statement. Should an exception occur while this code is being run, the code in the “catch” part of the statement will be run. After the try/catch is complete, the code in the “finally” division will be run. Note that the “finally” code will always run, regardless of whether there was an exception.
Example:
try
{
var a = 1;
var c = a + b;
}
catch(e)
{
document.write('An exception occurred.');
}
finally
{
document.write('The Finally block always runs.');
}
The preceding code goes into the catch block because the “b” variable was never defined and therefore cannot be added to “a.”