android-logo

Javascript try...catch


The try-catch-finally block in JavaScript offers an error-handling method to capture runtime issues. JavaScript is a loosely-typed language. It does not produce errors at compile time.

Syntax


try
{
    // code 
}
catch(error)
{
    // If an error occurs, this code block will be executed.
}
finally{
    // Whether or not an error occurs, this code block will be executed.
}


Lets try to generate an error without try catch block


var value  =  add (5, 10);
console.log(value)

Output

var value  =  add (5, 10);
              ^
ReferenceError: add is not defined


Now lets handle same error using try catch block


try
{
    var value  =  add (10, 20);
}
catch(error)
{
    console.log("Catch executed")
}

Output

Catch executed


finally block

Whether or not an error occurs, finally code block will be executed. Lets take an example of finally block.


try
{
    var value  =  add (10, 20);
}
catch(error)
{
    console.log("Catch executed")
}
finally{
    console.log("finally executed")
}

Output

Catch executed
finally executed


throw

throw is used to create your own exception.


try {
    throw "Custom error occurred";
}
catch(error) {
   
}


Example 2


try 
{
    throw {
        code: 101,
        message: "Error occurred"
    };
}
catch (error) {
    console.log(error.code + "- " + error.message);
}


Lets throw an exception using throw


const number = -10;
try {
    if(number > 0) {
        console.log('true');
    }
    else {

        // custom throw statement
        throw new Error('false');
    }

    // Below code executes only if the statement is true
    console.log('Positive number');
}
catch(error) {
    console.log('Message: ' + error);  
}

Output

Message: Error: false


Now lets take an positive number


const number = 10;
try {
    if(number > 0) {
        console.log('true');
    }
    else {

        // custom throw statement
        throw new Error('false');
    }

    // Below code executes only if the statement is true
    console.log('Positive number');
}
catch(error) {
    console.log('Message: ' + error);  
}

Output

true
Positive number


previous-button
next-button

facebook-logo
twitter-logo
instagram-logo

2020 © All rights reserved.