Error Object in JavaScript

Error object is thrown when any error occurs in JavaScript.

Error object has 2 properties.

  1. name
  2. message

There can be below types of errors in JavaScript.

  1. ReferenceError
  2. SyntaxError
  3. TypeError
  4. RangeError
  5. EvalError
  6. URIError

Example on Error Object is given below.

In below example, since we have not defined x earlier in the code, error will be thrown. In catch block, we can handle that error.

try {
       console.log(“Checking exception” + x);
catch(error) {
       console.log(“Error message -> ” + error.message);
        console.log(“Finally block is always executed no matter error is thrown or not in try block!!”);

Throwing custom error

Below example illustrates how to throw custom error in JavaScript.

      var balance=0;
     if (balance==0)
          throw new Error(“balance is 0”)


         console.log(“Error thrown -> ” + err.message)

You may also like...