Error handling in JavaScript

JavaScript is a loosely-typed language. It does not give compile-time errors. So some times you will get a runtime error for accessing an undefined variable or calling undefined function etc.

try catch block does not handle syntax errors.

JavaScript provides error-handling mechanism to catch runtime errors using try-catch-finally block, similar to other languages like Java or C#.

Syntax:
try
{
    // code that may throw an error
}
catch(ex)
{
    // code to be executed if an error occurs
}
finally{
    // code to be executed regardless of an error occurs or not
}
  • try: wrap suspicious code that may throw an error in try block.
  • catch: write code to do something in catch block when an error occurs. The catch block can have parameters that will give you error information. Generally catch block is used to log an error or display specific messages to the user.
  • finally: code in the finally block will always be executed regardless of the occurrence of an error. The finally block can be used to complete the remaining task or reset variables that might have changed before error occurred in try block.

Let's look at simple error handling examples.

Example: Error Handling in JS
try
{
    var result  =  Sum(10, 20); // Sum is not defined yet
}
catch(ex)
{
    document.getElementById("errorMessage").innerHTML = ex;
}

In the above example, we are calling function Sum, which is not defined yet. So, try block will throw an error which will be handled by catch block. Ex includes error message that can be displayed.

The finally block executes regardless of whatever happens.

Example: finally Block
try
{
     var result  =  Sum(10, 20); // Sum is not defined yet
}
catch(ex)
{
    document.getElementById("errorMessage").innerHTML = ex;
}
finally{
    document.getElementById("message").innerHTML = "finally block executed";
}

throw

Use throw keyword to raise a custom error.

Example: throw Error
try
{
    throw "Error occurred";
}
catch(ex)
{
    alert(ex);
}

You can use JavaScript object for more information about an error.

Example: throw error with error info
try 
{
    throw {
        number: 101,
        message: "Error occurred"
    };
}
catch (ex) {
    alert(ex.number + "- " + ex.message);
}
Want to check how much you know JavaScript?