JavaScript try-catch-finally Statement Example

JavaScript try-catch-finally Statement Example

In this tutorial, you will learn about the try…catch…finally statements to handle exceptions in JavaScript with the help of examples.

The try statement specifies the code block that will be executed (to try). The catch statement specifies a code block that will handle any errors that occur. The finally statement specifies a code block that will be executed regardless of the outcome.

To manage exceptions, the try, catch, and finally, blocks are utilized (a type of error). Before you can learn about them, you must first understand the many sorts of programming errors.

Types of Errors

There are 2 types of errors in programming:

  • Syntax Error: A syntax error. If you type consol.log(‘your result’);, the above program throws a syntax error. The given code contains an error in the spelling of the console.
  • Runtime Error: This sort of error occurs during program execution. Calling an incorrect function or variable, for example.

These runtime problems are referred to as exceptions. Let’s look at how you can handle these exceptions now.

JavaScript try-catch Statement

To manage exceptions, the try…catch statement is employed. Its syntax is as follows:

try {
    // body of try
} 
catch(error) {
    // body of catch  
}

The core code is contained within the try block. If an error happens while executing the try block, it moves to the catch block. The catch block handles errors in accordance with the catch statements.

If there is no error, the code within the try block is performed and the catch block is bypassed.

Example 1: Display Undeclared Variable

// program to show try...catch in a program

const numerator= 100, denominator = 'a';

try {
     console.log(numerator/denominator);

    // forgot to define variable a      
    console.log(a);
}
catch(error) {
    console.log('An error caught'); 
    console.log('Error message: ' + error);  
}

Output:

NaN
An error caught
Error message: ReferenceError: a is not defined

A variable is not defined in the preceding program. The application throws an error when you try to print the variable. The catch block catches that error.

JavaScript try-catch-finally Statement

To manage exceptions, you may also utilize the try…catch…finally statement. When the code runs successfully or if an error occurs, the finally block is executed.

The syntax of the try-catch-finally block is as follows:

try {
    // try_statements
} 
catch(error) {
    // catch_statements  
}
finally() {
    // codes that gets executed anyway
}

Example 2: try…catch…finally Example

const numerator= 100, denominator = 'a';

try {
     console.log(numerator/denominator);
     console.log(a);
}
catch(error) {
    console.log('An error caught'); 
    console.log('Error message: ' + error);  
}
finally {
     console.log('Finally will execute every time');
}

Output:

NaN
An error caught
Error message: ReferenceError: a is not defined
Finally will execute every time

An error happens in the preceding program, and that error is caught by the catch block. In either case, the final block will be executed ( if the program runs successfully or if an error occurs).

Note: You must employ a catch or finally statement following the try statement. Otherwise, the program will fail with an Uncaught SyntaxError: Missed catch or finally after an attempt.

JavaScript try…catch in setTimeout

 The try-catch won’t catch the exception if it happened in “timed” code, like in setTimeout(). For example,

try {
    setTimeout(function() {
        // error in the code
    }, 3000);
} catch (e) {
  console.log( "won't work" );
}

The preceding try…catch will fail because the engine has already exited the try…catch construct and the function is executed later.

To catch an exception inside a timed function, the try..catch block must be inside that function. As an example,

setTimeout(function() {
    try {
        // error in the code
    } catch {
        console.log( "error is caught" );
    }
}, 3000);

To use user-defined exceptions, combine the throw statement with the try…catch sentence. For instance, a specific number is divided by 0. If you want to treat Infinity as an error in the program, you can handle it by throwing a user-defined exception with the throw statement.

You may like:

continue and break Statements in JavaScript

try catch finally javascript try catch finally javascript try catch finally javascript try catch finally javascript try catch finally javascript try catch finally javascript try catch finally javascript

This Post Has One Comment

Leave a Reply