JavaScript: Exception Handling

Exception handling in JavaScript is extremely similar to that in C# or Java. Js utilizes the familiar try-catch blocks to capture exceptions and handle them. You simply wrap code that might throw an exception in the try and then provide a catch to handle the captured exceptions.

Unlike C# and Java, JavaScript does not allow multiple catch blocks nor does it handle capturing exceptions based on specificity. For this you must implement your own code by checking the exception name or using reflection methods to identify the exception types you are after. This is a little cumbersome but doable.

'use strict';

// Exception Handling
//  1. Use 'throw' to create and throw an Exception
//  2. Use the 'name' property to give the Exception an identifiable name
//  3. Use the 'message' property to give the Exception a meaningful message for the user
//  4. Standard Try-Catch as we are used to in Java and C#
//  5. Place code which might create an error in the 'try' block
//  6. Place rescue code in the 'catch' block
//  7. 'try' blocks can only have one 'catch' and one only
//  8. Must check Exception name in order to handle more than one type of Exception at a time

try{
    // Code that can cause an error during execution

    // Code actually throwing an Exception
    throw {
        name: "CustomErrorType",
        message: "I just threw an error at you."
    }
}catch(error){
    if(error.name === "SomeOtherError"){
        // Do something here
    }

    if(error.name === "CustomErrorType"){
        // Code to rescue processing from the error
        console.log("Captured and error: " + error.name);
        console.log("Its message is: " + error.message);
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s