The try…catch block is used to catch exceptions that may occur during code execution in JavaScript.
It allows us to handle errors that occur during execution, without interrupting the overall program flow (handling it in a controlled way).
The basic syntax of try...catch is as follows:
try {
// Code that may generate an error
} catch (error) {
// Code that executes if an error occurs
} finally {
// Code that always executes, regardless of whether an error occurred or not
}
- try: Contains the block of code to be executed that could throw an exception.
- catch: Catches the exception thrown in the
tryblock and allows handling the error. finally(optional): Contains code that always executes, whether an error occurred or not.
How to use try...catch
Let’s see a simple example to understand how try...catch works:
try {
let undefinedVar; // Not initialized
// This will throw a TypeError
console.log(undefinedVar.toString());
} catch (error) {
console.log("Error caught:", error.message);
}
// would show
// Error caught: Cannot read properties of undefined (reading 'toString')
In this example, the TypeError is caught and handled in the catch block.
Using finally
The finally block is optional and is used to execute code that must always run (regardless of whether an error occurs or not).
try {
let undefinedVar; // Not initialized
// This will throw a TypeError
console.log(undefinedVar.toString());
} catch (error) {
console.log("Error caught:", error.message);
} finally {
console.log("This will print no matter what");
}
In this case, regardless of whether an error occurs, the message “This will print no matter what” will always be displayed.
Specific error handling
Sometimes it’s useful to distinguish the type of errors we’ve caught. For this, we can use instanceof inside the catch block.
try {
// Code that may fail
} catch (error) {
if (error instanceof TypeError) {
console.log("Error type:", error.message);
} else {
console.log("Other type of error:", error.message);
}
}
