What is the optional catch binding in JavaScript?
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 arguumenttry{} catch(err) { // error argument is present}// try...catch without error arguumenttry{} 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.
Explanation
In the above code:
- Line 8: We parse a string
abcas a JSON using theJSON.parsemethod. 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.