Sunday, September 22, 2024
Google search engine
HomeLanguagesJavascriptHow to catch an “ReferenceError” with “onerror” ?

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

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>neveropen:- 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>neveropen:- 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("neveropen Error: ");
            console.log("Stack: " + stack);
        };
  
        var x = y; // ReferenceError: foo is not defined
    </script>
</head>
  
<body>
    <div>neveropen:- OneError</div>
</body>
  
</html>


Output:

 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments