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

JavaScript Making Uppercase

What is this Keyword in Javascript ?

What is Alert Method in Window Object in Javascript ?

JavaScript Taking the Square Root of a Number

What is Console Object in Javascript ?