The try...catch
statement is used to handle exceptions.
try {
// Statements
}
catch (error) {
// Statements
}
finally {
// Statements
}
The try
block contains codes, that can throw exceptions. The catch
block runs when an exception occurs in code present inside the try
block. The finally
block runs regardless.
const number = "this is not a number";
try {
if(isNaN(number)) {
throw "Please only enter a number";
}
}
catch (error) {
console.log(error);
}
finally {
console.log("this runs regardless";
}
/* Prints:
Please only enter a number
this runs regardless
*/
The try
block tries to run the code without exception, if it succeeds then it moves on to the finally
block. If it throws an exception then it goes to the catch block, and then finally to the finally
block.