Exception Handling

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.


How to handle exception handling



try

try is a code block used to wrap exception code. The code will run normally, but if any error is occurs, it will throw error.

 try{
}

throw

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


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

Catch

catch statement is used to catch the error throwed by try.


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 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);   
    }