JavaScript Try Catch Finally

JavaScript try catch finally statement are handle exceptions gracefully. In JavaScript, exception handling is a powerful mechanism to deal with errors.

JavaScript try statement test (execute) the block of code for a specific response.

JavaScript catch statement caught the errors that are thrown inside try block.

JavaScript finally statement always execute after the try catch block.

Syntax
   try {
        Statements
    }
    catch(exception identifier){ 
        Statements
    }
    finally {
        Statements
    }

JavaScript try block of code try to execute in-case error occur in execution flow, find the error type of that particular error and related exception catch block will execute.

All error types and messages are write in catch block.

catch and finally statement are optionally. Let's see following example,

JavaScript try...catch Statement

Example This example asking() function try to call in try block but this function is not defined and catch block exception will execute ReferenceError: asking is not defined.

<script>
    function welcome(){
        document.writeln("welcome() : Hello world!");
    }
    function bye(){
        document.writeln("bye() : Good bye!");
    }
    
    try{
        welcome()
        asking()
    }
    catch(e){
        document.writeln("asking() : " + e);
    }
        
    bye()
</script>

Run it...   »

Example Result

JavaScript try...finally Statement

Example This example represent finally block of code execute after the try block of code.

<script>
    function welcome(){
        document.writeln("welcome() : Hello world!");
    }
    function bye(){
        document.writeln("bye() : Good bye!");
    }
    
    try{
        welcome()
    }
    finally{
        bye()
    }
</script>

Run it...   »

Example Result

JavaScript try...catch...finally Statement

Example JavaScript finally statement is optional If you specifies finally block, that will execute always.

finally statement use when you need to execute some code after the try block.

<script>
    function welcome(){
        document.writeln("welcome() : Hello world!");
    }
    function bye(){
        document.writeln("bye() : Good bye!");
    }
    
    try{
        welcome()
        asking()
    } catch(e){
        document.writeln("asking() : " + e);
    } finally{
        bye()
    }
</script>

Run it...   »

Example Result

JavaScript try...catch...finally Statement with break

Example JavaScript break, continue keyword skip the remaining try block of code as well catch block, immediately control transfer to the finally block.

<script>
    try{
        for(var i = 0; i < 5; i++){
            document.writeln("i: " + i);
            if (i == 3){
                break;
            }
        }
        }catch(e){      // Skip catch block
        document.writeln(e.message);
    }
    finally{
        document.writeln("last i: " + i);
    }
</script>

Run it...   »

Example Result