In JavaScript, the try...catch
statement is used to handle errors that may occur during the execution of a block of code. The try
block contains the code that may throw an exception, and the catch
block contains the code that will be executed if an exception is thrown. Here's an example:
try {
// code that may throw an exception
doSomething();
} catch (error) {
// code to be executed if an exception is thrown
console.error(error);
}
In this example, if the doSomething()
function throws an exception, the code in the catch
block will be executed and the error will be logged to the console. If no exception is thrown, the catch
block will be skipped.
You can also use the finally
block to specify code that should be executed regardless of whether an exception is thrown or not. The finally
block will be executed after the try
block and any matching catch
block:
try {
// code that may throw an exception
doSomething();
} catch (error) {
// code to be executed if an exception is thrown
console.error(error);
} finally {
// code to be executed regardless of whether an exception is thrown
cleanup();
}
In this example, the cleanup()
function will be called regardless of whether an exception is thrown or not.