try/catch/finally Statements

By: Dusty Arlia
Published on Thursday, May 2, 2013, 04:15 PM
Last Updated on Friday, July 17, 2015 at 3:04 PM
Total Updates: 4

JavaScript uses the try/catch/finally statement to handle exceptions that are thrown. Here is the basic syntax of the try/catch/finally statement:

try {
//Place your code here
//If a problem occurs throw an exception
//with a throw statment
//or by calling a method that
//throws an exception
catch (thrown_value){
//This block only executes only if the
//try block throws an exception. The code
//here is able to access the local variable thrown_value
//which holds the value that was thrown in the the try
//block. This code may handle the exception, ignore it, or
//rethrow the exception with a throw statement
finally {
//[Optional] If any part of the try block executes this statement 
//block will always execute if this clause is included.
//This block of code, if included, is usually used to clean up after 
//the try block.

Here is a real example:

var full_name = 1234;

try {
    if (full_name != NaN) throw ("Please do not enter a number for a name");
} catch (new_error) {
} finally {
    full_name = "";

The value associated with the exception is passed as an argument to the parameter that follows the catch keyword. In the example above, the parameter is called thrown_value. This parameter is a variable with block scope.

If an exception is thrown in the try block and there is no catch clause to handle the exception, the JavaScript interpreter will first execute the finally block before jumping to the nearest catch clause.

If there is a jump statement inside the finally block or a method that throws an exception, then the JavaScript interpreter abandons the jump statement it was handling to execute the new jump statement.

For example, if a finally clause throws an exception, then that exception executes while the one that was being processed is abandoned. If a finally clause has a return statement in its block, the return statement is run as normal, even if the exception being processed hasn't been handled yet.

The try and finally statement blocks can be used without needing a catch clause. In this situation the finally clause is guaranteed to run. The finally clause will clean up after the try block.