The try-catch Rule in JavaScript
JavaScript
Error Handling
Frontend

The try-catch Rule in JavaScript

Understand the try-catch rules for handling exceptions and errors in your JavaScript applications.
2 min read

Basic Rules of Error Handling

Here are the basic rules of handling errors:

  • First, the code inside the try gets executed.
  • If there are no errors in the try-block, the catch-block will be ignored and will not be executed.
  • If there is an error in the try block, the execution of the try block will be suspended and the control will move to the catch block. In the catch block you can find the error details and do the needful.

Now, take a look into the code snippet below:

JS
try {
    console.log("execution starts here");
    abc;
    console.log("execution ends here");
} catch (err) {
    console.error("An Error has occured");

    console.log(err.name)
    console.log(err.message)
    console.log(err.stack)
}

After the first console.log(), the JavaScript engine will encounter an ReferenceError because the line with the code abc will not make sense to it. Hence, it will throw the error without executing the next line of code.

Then, the control will go to the catch-block. In the catch-block we get the error information like, name, message, stack trace, etc. You can even rethrow the error from the catch-block so that it can be handled elsewhere.

Want to learn further?

Check out the Error Handling in JavaScript to learn real-life use cases with code.

Day 14: Error Handling in JavaScript is Easy. Let's MASTER 🤩 - Dive into handling errors and exceptions in JavaScript code. This session will enable you to understand different types of errors, how to handle them, how to create custom errors, and different ways to deal with error scenarios.

Learn Full Stack

with tapaScript

By clicking Sign Up you re confirming that you agree with our Terms and Conditions.

newsletter

Don't forget to connect with us on