Error Handling

Error Handling

Sometimes our script can have errors. Execution of the program halts when an error occurs. We can use the try-catch method to catch errors and maintain the flow of execution.

As we can see only the first instruction is executed and then the flow of execution stops.

The try-catch syntax has two main blocks try and catch.

First, the try block is executed and if no error is found the catch block is ignored. If there is an error the catch block is executed.

Try catch works synchronously.


Error Object & Custom Errors

Error object has two main properties error.name and error.message.

Throwing custom errors

We can throw custom errors by using throw syntax.


Finally Clause

The try-catch construct may have one more code clause: finally.

If it exists it runs for all cases. This block is executed after try if there are no errors or after catch if there are no errors.