JavaScript Error Handling: Try, Catch, and Finally

Error is a term referring to an unexceptional affair that creates trouble in the expected execution.

The errors can occur due to many reasons such as access not existing variables, invalid syntax, data type mismatch, etc. These errors are essential to handle to construct a secure stable application.

Also Read: NodeJS Errors: List of 6 Types of NodeJS Errors

Handling JavaScript Errors with Try-Catch-Finally Blocks

Error handling can be handled by using a try-catch-finally block. If there is no error then only the statement inside the ‘try’ block will execute and only if an error occurs then the statements inside the ‘catch’ block will execute. The ‘finally’ block is an optional block that is executed every time after the try-catch block completes its execution whether the error occurs or not.

Example:

try{
    var result = Sum(10, 20);
    console.log(result);
}
catch(error){
    console.log('Error occured');
}
finally{
    console.log('Finally block executed');
}

Output:

Error occured
Finally block executed

Managing Specific JavaScript Errors

Writing a try-catch-finally block for handling all types of errors might not be a good idea, rather we can handle errors based on their type.

In JavaScript, an error has three basic properties:

  • name: It is the type of error.
  • message: It is the actual error message.
  • stack: It is the stack trace when an error is thrown.

We can use conditional statements to check for a particular type of error using its name property to handle it accordingly.

Example:

try
{
    var result  =  Sum(2, 3); // Sum is not defined yet
    console.log(result);
}
catch(error)
{
    if(error.name == 'ReferenceError')
    {
        console.log('Sum is not defined yet');
    }
}

Output:

Sum is not defined yet

Throwing and Handling Custom JavaScript Errors

Handling errors can be a pain in JavaScript as many times it doesn’t throw an error, the programs will silently get failed or not end up with the expected output.

In that case, we have to create a way to throw custom errors based on multiple conditions and then handle them accordingly.

Creating Custom JavaScript Errors

A custom error can be thrown using the throw keyword.

We can implement several conditional statements to check for expected execution, if not then throw a custom error. 

Example:

JavaScript doesn’t throw an error when performing a mathematical operation on strings, it can be possible that a user that uses the Sum function passes a string as an argument mistakenly, then the Sum function will concatenate the values together instead of adding them.

If you want to read more about it, we have handled this problem in another tutorial NodeJS Convert String To Int – A Step-by-Step Guide.

The throw can be used to produce an error if the argument passed is not a number. 

Below is the code having a condition statement to check for the arguments passed are numbers, if not then an error is thrown.

function Sum(a, b)
{   
    if(typeof a != 'number' || typeof b != 'number'){
        throw new Error('Arguments must be numbers');
    }
    return a + b;
}

Handling Custom JavaScript Errors

In the previous example, we have thrown an error if the arguments passed are not numbers when calling the Sum function. Let’s handle that error using this try-catch-finally block.

Example:

function Sum(a, b)
{   
    if(typeof a != 'number' || typeof b != 'number'){
        throw new Error('Arguments must be numbers');
    }
    return a + b;
}

try
{
    var result  =  Sum('2', 3); 
    console.log(result);
}
catch(error)
{
    if(error.name == 'ReferenceError')
    {
        console.log('Sum is not defined yet');
    }
    else
    {
        console.log('Error Message: ' + error.message);
    }
}

Output:

Error Message: Arguments must be numbers

Summary: Best Practices for Managing JavaScript Errors

JavaScript is a loosely-typed language, errors occur several times, and to make a secure stable application, it must be handled correctly. The error can be handled by using the try-catch-finally block, we can also check for the error type using the name property to handle it differently. We can also implement functionality on various stages to check for the unexcepted execution then throw custom errors using the throw keyword and handle them according. Hope this tutorial helps you to understand the approach to handling errors in JavaScript.

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try…catch

Aditya Gupta
Aditya Gupta
Articles: 151