Exception Handling using try catch

For error handling or exception handling in javascript, we can use try catch.

It is compulsory to handle runtime errors in javascript. Errors can block the whole code.

javascript Try Catch
JavaScript Exception Handling using Try Catch

By using error handling, our program will execute even if any error occurs.

Forms of try statement

  1. try ... catch
  2. try ... finally
  3. try ... catch...finally


try

try is a code block used to wrap exceptions. The code will run normally, but if any error occurs, try will throw error using string or error Object.

Try with Condition


    try{
        if(error){ throw "error";}
    }
    catch(err){
        console.log(err);
    }

Try without Condition


try{
var x=navigator.getBattery().then((x)=>{console.log(x.level*100+"%")});
console.log(x);
}   
catch(err){
console.log(err);
}

throw

throw block is used to throw exceptions. throw can send a string error message, or error object.


    var x=3;    
    try{
        if( x<0){  throw "negative no";}    
        if( x==0){  throw "zero";}    
    }
    catch(error)

Catch

catch statement is used to catch the error thrown by try block.


var x=3;    
    try{
        if( x==0){  throw "zero ";}    
        if( x<0){  throw "negative no";}    
    }
    catch(error)

Error Object

We can also error object to handle runtime errors.

Error Object Example


var x=3;    
    try{
        if( x==0){  throw  new Error("zero");}    
        if( x<0){  throw new Error("Negative Number");}    
    }
    catch(error){
        console.log(error);
    }           
  1. It is compulsory to use catch or finally after try block.

finally

finally block is used after catch block. finally block will always execute whether an error occurs or not. Lets says we want some output even if errors occurs, we can use finally block.


var x=3;    
    try{
        if( x==0){  throw  new Error("zero");}    
        if( x<0){  throw new Error("Negative Number");}    
    }
    
    catch(error){
        console.log(error)
    }
    
    finally{
        console.log("the number is ", x);   
    }