Core JavaScript

Intermediate JavaScript

JavaScript Reference



JavaScript try catch finally Statement


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

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

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

finally statement always execute after the try catch block.

	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 check following example,

Example (try...catch statement) : 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 :


Example (try...finally statement) : 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 :


Example (try...catch...finally statement) : 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 :


Example (break with try...catch...finally statement) : 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 :