Exceptions in JavaScript

JavaScript’s latest version added exception-handling capabilities. It provides try, catch and finally blocks to handle the exceptions.

Syntax of a try block with catch block:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
try{
//block of statements
}catch(exception_var){
}
try{ //block of statements }catch(exception_var){ }
try{
       //block of statements

}catch(exception_var){

}

Syntax of a try block with a final block:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
try{
//block of statements
} finally {
}
try{ //block of statements } finally { }
try{
       //block of statements

} finally {

}

Syntax of try block with catch and finally block:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
try{
//block of statements
}catch(exception_var){
}finally{
}
try{ //block of statements }catch(exception_var){ }finally{ }
try{
        //block of statements

}catch(exception_var){

}finally{

}

catch block:

The catch block is used for the exception handler. It is used after the try block.

Syntax:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
try{
//block of statements
}catch(exception_var){
}
try{ //block of statements }catch(exception_var){ }
try{
       //block of statements

}catch(exception_var){

}

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<body>
<p id="test"></p>
<script>
try {
showalert("Welcome guest!");
}
catch(error) {
document.getElementById("test").innerHTML = error.message;
}
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <p id="test"></p> <script> try { showalert("Welcome guest!"); } catch(error) { document.getElementById("test").innerHTML = error.message; } </script> </body> </html>
<!DOCTYPE html>
<html>
<body>
<p id="test"></p>
<script>
try {
showalert("Welcome guest!");
}
catch(error) {
document.getElementById("test").innerHTML = error.message;
}
</script>
</body>
</html>

Related topics: