Control Flow

Try Catch Block in JavaScript

A try-catch block is used to mitigate errors in code and prevent program crashing during runtime. It 'tries' a block of code that could give an error. If the error is caught, it will execute a different block of code rather than crash the program (throw an error).


Syntax
try {
    //code to try which may give an error
    if(errorCondition) throw "Error message"; //custom error throwing
}
catch(err) {
    //code to be run if error is caught
} 
finally {
    //code to execute regardless of whether or not error is caught
}

Notes

JavaScript has built in errors which will be thrown if a line of code gives the compiler problems. Custom errors, however, can also be thrown using if statements and an error condition.

'err' is an object which contains the error message thrown.


Example
var numerator = 5;
try {
    if(denominator == 0) throw "Denominator cannot be zero!";
    else {
        var result = numerator / denominator;
    }
} catch(err) {
    console.log(err);
}

See Also
Documentation

try...catch - JavaScript | MDN

Add to Slack

< Do-While Loop   |   Function Declaration >

© 2019 SyntaxDB. All Rights Reserved.