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
tryblock doesn’t cause program termination. - If an error is caused inside the
tryblock then the execution control is transferred tocatchblock. - In simple words,
trychecks for any error, andcatchreceives execution control when an error occurs and can handle it. Afterwards, the program is resumed as normal. - If no error occurs, then the
catchblock 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
tryblock is not executed. - When an exception occurs, the
catchblock 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…catchblock to catch theTypeError - 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
catchblock

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
- Whatever variable you declare inside the
tryorcatchblock 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
