Try, Catch and Finally in JavaScript (Error Handling)

Shuaib SiddiquiShuaib Siddiqui
2 min read

In JavaScript, try, catch, and finally are three keywords used for error handling.

try and catch blocks work together to catch and handle errors in your code. The try block contains the code that might throw an error, and the catch block contains the code that executes when an error is thrown.

Here is an example of how you can use try and catch:

try {
  // code that might throw an error
  const myArray = [1, 2, 3];
  console.log(myArray[4]);
} catch (error) {
  // code that handles the error
  console.log("Oops, something went wrong:", error);
}

In the above example, we are trying to access an index that doesn't exist in the myArray. This will throw an error, which will be caught by the catch block. The error message will be logged to the console.

The finally block is used to execute code that should run regardless of whether an error was thrown or not. For example:

try {
  // code that might throw an error
  const myArray = [1, 2, 3];
  console.log(myArray[4]);
} catch (error) {
  // code that handles the error
  console.log("Oops, something went wrong:", error);
} finally {
  // code that always runs
  console.log("The try-catch block is done.");
}

In the above example, the finally block will always execute, even if an error was thrown. This is useful for tasks like cleaning up resources or closing connections.

Summary

In summary, try, catch, and finally are important keywords for error handling in JavaScript. They allow you to catch and handle errors in your code and execute code that should always run, regardless of whether an error was thrown or not.

0
Subscribe to my newsletter

Read articles from Shuaib Siddiqui directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shuaib Siddiqui
Shuaib Siddiqui