in , ,

JavaScript try…catch…finally Statement

JavaScript try catch finally Statement
JavaScript try catch finally Statement

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

The try, catch and finally blocks are used to deal with exceptions (a type of an error). Before you learn about them, you need to think about the sorts of mistakes in programming.

In this article, you will learn-

Definition and Usage

The try/catch/finally statement handles a few or the entirety of the blunders that may happen in a block of code, while as yet running code.

Errors can be coding blunders made by the programmer, errors because of wrong input, and other unforeseeable things.

The try statement allows you to characterize a block of code to be tried for mistakes while it is being executed.

The catch statement allows you to characterize a block of code to be executed, if a mistake happens in the try block.

The finally statement allows you to execute code, after try and catch, regardless of the result.

Note: The catch lastly proclamations are both discretionary, however you need to use one of them (if not both) while using the try statement.

Tip: When a mistake happens, JavaScript will normally stop, and create an error message. Use the throw statement to make a custom blunder (throw an exception). In the event that you use throw together with try and catch, you can handle program flow and create custom error messages.

Types of Errors

In programming, there can be two sorts of mistakes in the code:

Syntax Error: Error in the syntax. For instance, in the event that you write consol.log(‘your result’);, the above program throws a syntax mistake. The spelling of console is a mistake in the above code.

Runtime Error: This type of error happens during the execution of the program. For instance,

calling an invalid function or a variable.

These errors that happen during runtime are called exceptions. Presently, let’s see how you can handle with these exceptions.


JavaScript try…catch Statement

The try…catch statement is used to handle the exceptions. Its syntax is:

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

The main code is inside the try block. While executing the try block, if any mistake happens, it goes to the catch block. The catch block handles the blunders according to the catch proclamations.

In the event that no blunder happens, the code inside the try block is executed and the catch block is skipped.


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

In the above program, a variable isn’t characterized. At the point when you try to print the a variable, the program throws a mistake. That blunder is trapped in the catch block.


JavaScript try…catch…finally Statement

You can likewise use the try…catch…finally articulation to deal with exceptions. The at last block executes both when the code runs effectively or if a mistake happens.

The syntax of try…catch…finally block is:

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

In the above program, a mistake happens and that blunder is caught by the catch block. The at last block will execute in any circumstance ( if the program runs effectively or if a mistake happens).

Note: You need to use get or at last articulation after try statement. Something else, the program will throw a mistake Uncaught SyntaxError: Missing catch or at long last after try.


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 above try…catch won’t work on the grounds that the engine has just left the try..catch construct and the function is executed later.

The try..catch block should be inside that function to catch an exception inside a time function. For instance,

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

You can likewise use the throw explanation with the try…catch articulation to use user defined exceptions. For instance, a specific number is divided by 0. In the event that you need to consider about Infinity as a blunder in the program, at that point you can throw a user-defined exceptions using the throw proclamation to deal with that condition.


Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.

salman khan

Written by worldofitech

Leave a Reply

JavaScript Symbol

JavaScript Symbol

JavaScript throw Statement

JavaScript throw Statement