Exceptions
Exceptions are errors that happen while JavaScript is running. JavaScript provides a mechanism to catch these errors when they happen.
try...catch...finally Statment
The try...catch...finally statement allows for testing of a block of code for exceptions (errors).
The try block contains the code to be run, the catch block contains the code to be executed if an error occurs, and the optional finally block contains code that is run regardless of errors.
The try...catch...finally
statement has the following syntax:
try
{
// Put an code that may
// produce errors here
}
catch(exception)
{
// Handle errors here. The
// exception object contains
// information about the error
console.log(exception);
}
finally
{
// This code always runs
// regardless of whether an
// error occurred
}
throw Statement
The throw statement allows for the creation of an exception.
The throw
statement is normally used in conjunction with the try...catch
statement to control program flow and accurately handle errors.
The throw
statement has the following syntax:
throw(exception)
The exception can be a string, integer, Boolean, or an object.