Exception Handling in JavaScript

Short Description

When a JavaScript statement generates an error, it is said to throw an exception.  Instead of proceeding to the next statement, the JavaScript interpreter checks for exception handling code.  If there is no exception handler, then the program returns from whatever function threw the exception.  This is repeated for each function on the call stack until an exception handler is found or until the top level function is reached, causing the program to terminate.

Code Details

  • In  Constructor Cat4() we throw an Exception in case our Object is not a Cat4 Object
  • in the Top Level Function we have a try … catch block to handle all Exceptions
  • Finally the Call Stack of the failing functions was displayed by looking at e.stack element
function Cat4(name) 
{
    if ( !(this instanceof Cat4))
    {
        throw new Error("Cat4 Constructor:: Constructor Cat4() was executed as JS Function");
    }
    ...
}

try 
{
    runConstructorTest4();    
} catch (e)
{
    logMessageNEW("Catching Exception in runConstructorTest4:: " + e.stack );
}

Output
14:34:17:654 Catching Exception in runConstructorTest4:: Error: Cat4 Constructor::
             Constructor Cat4() was executed as JS Function
    at Cat4 (http://localhost:8080/testObjectMaven/js/objectTest.js:89:15)
    at runConstructorTest4 (http://localhost:8080/testObjectMaven/js/objectTest.js:80:17)
    at initObjectsTest (http://localhost:8080/testObjectMaven/js/objectTest.js:15:5)
    at onload (http://localhost:8080/testObjectMaven/:13:38)

Reference

 

Leave a Reply

Your email address will not be published. Required fields are marked *