Everything you need to know about error handling in Javascript

Exception handling is the way that we can prevent abnormal program termination on runtime due to some Exception. For example

In the above case, instead of termination of the program, we can handle it by try…catch block.

  • Any error inside try block doesn’t cause program termination.
  • If an error is caused inside the try block then the execution control is transferred to catch block.
  • In simple words, try checks for any error, and catch receives execution control when an error occurs and can handle it. Afterwards, the program is resumed as normal.
  • If no error occurs, then the catch block is skipped.

Example :

In the above example, If we don’t pass the name then it results in an exception, and then the exception is handled in the catch block.

When we call the function checkName()without passingname:

  • An exception occurs when calculating the length.
  • When an exception has occurred, the remaining code below the current line in the try block is not executed.
  • When an exception occurs, the catch block receives an error object, which contains the details of the error.

try…catch…finally

The finally blocks is always executed even when there is no error inside the try block.

We can also use try…finally instead of try..catch like:

Example

Custom Errors

A custom error means throwing our own error.

The throw operator generates a custom error. For that we need to create an error object, then we can throw that ErrorObject.

Read about all available Errors in Javascript here on MDN.

Creating a custom exception class for throwing a custom exception:

Re-throwing an error

We can also re-throw the error which is caught in a catch block.

Consider that,

  • We have use a try…catch block to catch the TypeError
  • But there is another error that has occurred inside the type block which programmer is unaware.
  • To handle this situation we can re-throw the error which is not expected in catch block

ES10 Modification on Error Handling with Optional Catch Binding

Optional catch binding allows developers to use try/catch without the error parameter inside the catch block.

Some interesting things in try…catch

  1. Whatever variable you declare inside the try or catch block cannot be accessed outside.

2. The try..catchworks synchronously,

If an exception in setTimeout, then try..catch won’t work.

The above code can be transferred to

Leave a comment

Design a site like this with WordPress.com
Get started