JavaScript Error Object

The error object is a built-in JavaScript error object, which provides error information when an error occurs. basically the error object provides two properties :

  • name : The name property sets or returns an error name.
  • message : The message property sets or returns an error message ( or a string).

Error Name Values :

There are six different values can be returned by the error name property :

1. RangeError :  The RangeError is thrown when a number exceeds the maximum allowable range.

Example :
<html>
<body>
  <input type="button" onclick="MyFunc()" value="Click Here"/> 
  <p id="demo1"></p>
  <script>
    function MyFunc() {
      var x = 1.5;
      try {
        x.toFixed(1000); 
      } catch(err) {
        var text = "ErrorName : " + err.name + "<br/>";
        text += "Error : " + err.message;
        document.getElementById("demo1").innerHTML = text; 
      }
    }
  </script>
</body>
</html>
Output :



2. ReferenceError : The ReferenceError is thrown on the rare occasion that an invalid reference is used.

Example :
<html>
<body>
  <input type="button" onclick="MyFunc()" value="Click Here"/> 
  <p id="demo2"></p>
  <script>
    function MyFunc() {
      var x;
      try {
        x = y + 1; 
      } catch(err) {
        var text = "ErrorName : " + err.name + "<br/>";
        text += "Error : " + err.message;
        document.getElementById("demo2").innerHTML = text; 
      }
    }
  </script>
</body>
</html>
Output :



3. SyntaxError : The SyntaxError is thrown when some sort of syntax error has occured at runtime.

Example :
<html>
<body>
  <input type="button" onclick="MyFunc()" value="Click Here"/> 
  <p id="demo3"></p>
  <script>
    function MyFunc() {
      try {
        aval("alert('This is text)"); 
      } catch(err) {
        var text = "ErrorName : " + err.name + "<br/>";
        text += "Error : " + err.message;
        document.getElementById("demo3").innerHTML = text; 
      }
    }
  </script>
</body>
</html>
Output :



4. TypeError : The TypeError is thrown when an operand has an unexpected type.

Example :
<html>
<body>
  <input type="button" onclick="MyFunc()" value="Click Here"/> 
  <p id="demo4"></p>
  <script>
    function MyFunc() {
      var str = "Hello world.";
      try {
        str.toFixed(10);
      } catch(err) {
        var text = "ErrorName : " + err.name + "<br/>";
        text += "Error : " + err.message;
        document.getElementById("demo4").innerHTML = text; 
      }
    }
  </script>
</body>
</html>
Output :



5. URIError : The URIError is thrown when one of global's URI-related functions is used incorrectly.

6. EvalError : The EvalError is thrown when eval() function is used incorrectly. But in newer versions of JavaScript does not throw any EvalError. Use SyntaxError instead.


Next Topic :