Open In App

How to catch an “ReferenceError” with “onerror” ?

Improve
Improve
Like Article
Like
Save
Share
Report

The “ReferenceError” is a very common error that can occur when programming in JavaScript. The “onerror” event is a great way to catch these errors and prevent them from causing your program to crash.

What is a “ReferenceError”?

A “ReferenceError” occurs when your program tries to access a variable or object that does not exist. This can happen when you misspell the name of a variable, or when you try to access an object that has not been initialized yet.

Example: Below is the code and output of the error:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script>
        var x = y; // this will cause a "ReferenceError"
    </script>
</head>
  
<body>
    <div>GeeksforGeeks:- OneError</div>
</body>
  
</html>


Output:

 

How to catch “ReferenceErrors” with “onerror”?

The “onerror” event is fired whenever an error occurs in your program. You can use this event to catch “ReferenceErrors” and prevent them from crashing your program.

Example 1: In the following example, we will use the “onerror” event to catch a “ReferenceError” and display an error message. Below is the full working code example:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script>
        window.onerror = function (error, url, line) {
            alert("Error: " + error + "\nURL: " + 
                  url + "\nLine: " + line);
        };
  
        var x = y; // this will cause a "ReferenceError"
    </script>
</head>
  
<body>
    <div>GeeksforGeeks:- OneError</div>
</body>
  
</html>


Output:

 

Example 2: In this example, we will use the “onerror” event to catch a “ReferenceError” and display an error message. We will also use the “stack” property to display the call stack of the error. Below is the full working code example:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script>
        window.onerror = function (error, url, line, column, stack) {
            console.log("GeeksforGeeks Error: ");
            console.log("Stack: " + stack);
        };
  
        var x = y; // ReferenceError: foo is not defined
    </script>
</head>
  
<body>
    <div>GeeksforGeeks:- OneError</div>
</body>
  
</html>


Output:

 



Last Updated : 17 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads