Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptHow to rethrow an exception in JavaScript, but preserve the stack?

How to rethrow an exception in JavaScript, but preserve the stack?

Stack trace conveys some portion of the data whenever an exception is thrown. The stack trace is a collection of all the methods used in the program. It starts with the method that throws an exception and ends with the method that catches the exception. In case if an exception is re-thrown, the stack trace is restarted at the current method. Thus the list of methods calls between the method that throws the exception and the current method is lost. One way to avoid this is to catch the error and store it locally and then re-throw the error. However, in JavaScript, there is no rethrow() function. Thus we throw the original error occurred. To understand the above context, refer to the following example.

Example 1: In a class test, Radha is supposed to answer the questions asked by the teacher. The teacher gives Radha a number and asks her if the given number is a valid day number and if yes then specify the corresponding day. If the given day number is invalid Radha should answer “Invalid Day Number”. If we run the code the embedded page will show the stack trace. It will show the error is originating at day() and then was re-thrown at month() and finally caught in the year(). Since 8 is out of bound so the output is displayed as Invalid day.

Input: 8 
Output:Error originated in day() and was thrown
 Invalid day
 Error was caught and rethrown in month()
 Invalid day
 Error was finally caught in year()
 Invalid day
  • Program:




    <!DOCTYPE html>
    <html>
      
    <head>
        <script>
            year();
              
            // For the year //
            function year() {
                try {
                    month();
      
                } catch (e) {
                    console.log(
    'Error was finally caught in year():', e.message);
                    alert(e.stack);
                }
            }
      
            // Fo the month //
            function month() {
                try {
                    day();
                } catch (e) {
                    console.log(
    'Error was then caught and rethrown in month():', e.message);
                    throw (e);
                }
            }
      
            function day() {
                var d = 8;
                var days = [
                  'Mon', 'Tue', 'Wed'
                  'Thurs', 'Fri', 'Sat', 'Sun'];
                try {
                    d = d - 1;
                    if (days[d] != undefined)
                        console.log("valid day:", days[d]);
                    else
                          
                        // Message is "Invalid day"
                        throw new Error("Invalid day"); 
                } catch (e) {
                    console.log(
    "Error originated in day() and was thrown:", e.message)
                    throw (e);
      
                }
            }
        </script>
    </head>
      
    <body>
        <h1>Welcome To Geeksforneveropen</h1>
    </body>
      
    </html>                        

    
    
  • Output:
    Error originated in day() and was thrown:
     Invalid day
     Error was then caught and rethrown in month():
     Invalid day
     Error was finally caught in year():
     Invalid day

Example 2: Number 5 is a valid day number, therefore, no error is thrown. Hence we get the output as a valid day.

Input: 5
Output:
valid day:
Fri
  • Program:




    <!DOCTYPE html>
    <html>
      
    <head>
        <script>
            year();
      
            function year() {
                try {
                    month();
      
                } catch (e) {
                    console.log(
    'Error was finally caught in year()', e.message);
                    alert(e.stack);
                }
            }
      
            function month() {
                try {
                    day();
                } catch (e) {
                    console.log(
    'Error was caught and rethrown in month()', e.message);
                    throw (e);
                }
            }
      
            function day() {
                var d = 5;
      
                var days = [
                  'Mon', 'Tue', 'Wed'
                  'Thurs', 'Fri', 'Sat', 'Sun'];
                try {
                    d = d - 1;
                    if (days[d] != undefined)
                        console.log("valid day:", days[d]);
                    else
                        throw new Error("Invalid day");
                } catch (e) {
                    console.log(
    "Error originated in day() and was thrown:", e.message);
                    throw (e);
      
                }
            }
        </script>
    </head>
      
    <body>
        <h1>Welcome To Geeksforneveropen</h1>
    </body>
      
    </html>

    
    
  • Output:
    valid day:
     Fri
  • 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