How to Handle Exceptions in JavaScript ?

JavaScript uses the try...catch...finally statement as well as the throw operator to handle exceptions.

You can catch user-defined and runtime exceptions, but you cannot catch JavaScript syntax errors.

Try - wraps suspicious code that may throw an error in try block.

Catch - Write code to do something when error occurs in catch block. The catch block can have parameters which will give you error information. Usually, catch block is used to log an error or display specific messages to the user.

Finally - code in finally block will always be executed regardless of the occurrence of an error. The finally block is usually used to complete the remaining task or reset variables that might have changed before error occurred in try block.

You May Interest

What are the Variable Naming Conventions in JavaScript ?

What is Code Smell in Javascript ?

JavaScript Making Uppercase

JavaScript Making Lowercase

What is Event Capturing in Javascript ?