Skip to main content

Command Palette

Search for a command to run...

Error Handling in JavaScript: Try, Catch, Finally

Updated
•2 min read•View as Markdown

Errors in JavaScript occur due to issues or conflicts in the code during execution. These can be syntax errors, runtime errors, or logical mistakes that disrupt the normal flow of the program.
If not handled properly, these errors can crash the entire application. Even a small error in one part of the code can affect other functionalities and potentially bring down multiple services.

Using try/catch Blocks

We use try/catch to handle errors gracefully. The code inside try is executed, and if an error occurs, control moves to catch.

try {
  const result = JSON.parse("invalid json");
  console.log(result);
} catch (error) {
  console.log("Error occurred:", error.message);
}

throw errors using the Error class, and access details like the message and error stack.

try {
  throw new Error("Something went wrong!");
} catch (error) {
  console.log(error.message);
  console.log(error.stack); // call stack
}

finally Block

The finally block always runs, whether an error occurs or not. It is useful for cleanup tasks.

try {
  console.log("Trying...");
} catch (e) {
  console.log("Error");
} finally {
  console.log("Always runs");

// say, close a modal
}

In frontend , this is useful for things like closing loaders or modals after an operation completes (handle loading state).


Throwing Custom Errors
create custom errors using new Error() to provide meaningful messages.

function withdraw(amount) {
  if (amount > 1000) {
    throw new Error("Insufficient balance");
  }
}

try {
  withdraw(2000);
} catch (e) {
  console.log(e.message);
}

Why Error Handling Matters

Error handling prevents the application from crashing unexpectedly. It ensures that even if something goes wrong, the rest of the application can continue to function properly and provide a better user experience.