The try, catch and finally blocks are used to handle exceptions (a type of an error). Before you learn about them, you need to know about the types of errors in programming.
JavaScript try...catch Statement:
The try...catch statement is used to handle the exceptions. Its syntax is:
try {
// body of try
}
catch(error) {
// body of catch
}
The main code is inside the try block. While executing the try block, if any error occurs, it goes to the catch block. The catch block handles the errors as per the catch statements.
If no error occurs, the code inside the try block is executed and the catch block is skipped.
JavaScript try...catch...finally Statement:
You can also use the try...catch...finally statement to handle exceptions. The finally block executes both when the code runs successfully or if an error occurs.
The syntax of try...catch...finally block is:
try {
// try_statements
}
catch(error) {
// catch_statements
}
finally() {
// codes that gets executed anyway
}
Note: You need to use catch or finally statement after try statement. Otherwise, the program will throw an error.
JavaScript try...catch in setTimeout:
The try...catch won't catch the exception if it happened in "timed" code, like in setTimeout(). For example:
try {
setTimeout(function() {
// error in the code
}, 3000);
} catch (e) {
console.log( "won't work" );
}
The above try...catch won't work because the engine has already left the try..catch construct and the function is executed later.
The try..catch block must be inside that function to catch an exception inside a timed function. For example,
setTimeout(function() {
try {
// error in the code
} catch {
console.log( "error is caught" );
}
}, 3000);
You can also use the throw statement with the try...catch statement to use user-defined exceptions. For example, a certain number is divided by 0. If you want to consider Infinity as an error in the program, then you can throw a user-defined exception using the throw statement to handle that condition.
Top comments (0)