Trusted answers to developer questions

What is the optional catch binding in JavaScript?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

Overview

In JavaScript, we use the optional catch binding function to skip the error argument of the catch block in a try...catch statement.

Syntax

// try...catch with error arguument
try{
} catch(err) { // error argument is present
}
// try...catch without error arguument
try{
} catch{ // error argument is skipped
}
Optional catch binding

Note: This feature was added in the ES10/2019.

The error argument contains the reason and cause of the exception.

The optional catch binding can be used when we need to handle the error but are not interested in the error's cause.

Example

Let's use the optional catch binding for handing the JSON parse exception.

Console
Using optional catch binding

Explanation

In the above code:

  • Line 8: We parse a string abc as a JSON using the JSON.parse method. However, this will throw an error because it is not a valid JSON string.
  • Line 9: We skip the error argument in the catch block, as it is obvious that if any error occurs it will be due to the invalid JSON data.

RELATED TAGS

javascript
Did you find this helpful?