D DevBrainBox

JavaScript Try & Catch

JS

What is try...catch?

try...catch is a way in JavaScript to handle errors (exceptions) without breaking the entire program.

It allows you to try a block of code that might throw an error, and if an error happens, it catches it so your program can react gracefully.

try {
 // Code that might throw an error
} catch (error) {
 // Code to handle the error
}

Catching an error

try {
  console.log("Start of try block");
  let result = 10 / x; // 'x' is not defined
  console.log("This will not run");
} catch (err) {
  console.log("An error occurred:", err.message);
}

console.log("The script continues...");
Output:
Start of try block
An error occurred: x is not defined
The script continues...

How does it work?

BlockPurpose
tryRuns code that might fail
catchRuns if an error happens in the try block, gives you the error object

finally block (optional)

You can also add a finally block. It runs no matter what, after try and catch.

try {
  console.log("Trying...");
  throw new Error("Oops!");
} catch (e) {
  console.log("Caught:", e.message);
} finally {
  console.log("This runs always");
}
  • try – runs risky code.
  • catch – runs if there’s an error, gives you the error object.
  • finally – always runs, useful for clean-up.

On this page