Implementing Exception Handling



Structured error handling in JavaScript is achieved with the try…catch…finally construct. Good defensive programming also includes checking for null values, where appropriate, to prevent errors.

In addition to handling errors, code can raise custom errors as needed to send error information back to a running program from custom objects or libraries.

Implementing try...catch...finally constructs

The try…catch…finally construct handles exceptions that occur during program processing. It enables you to see what kind of error occurred and to do what’s appropriate with it.

If try…catch…finally isn’t implemented in the program, the errors would be treated as unhandled and could cause the browser to crash or, at a minimum, display many annoying message boxes to users.

To prevent such issues, you need to wrap the code in a try block:

<body>
<!--  Exception Handling Browser Support  -->
<script type="text/javascript">
    var browserSupport = function() {
        try {
            window.dosomeunsupportedmethod();
        } catch (e) {
            alert("Browser does not support the desired functionality.");
    }
}
</script>
</body>

The try…catch block is divided into three parts:

  • the try portion executes code that is subject to break. It must be followed by either exactly one catch block or one finally block or one of both. When exception occurs, the exception is passed to the catch block
  • the catch block receives an exception object with information about the error
  • the finally block block is optional, but if included, it will always execute regardless if an exception has occurred

The catch block is where the error can be handled as appropriate for the application. The catch block receives a parameter that is an exception object.

The following Table shows the properties for the exception object.

Property Description
message A textual description of the error that occurred
number A numeric error code
name The name of the exception object

Variable scope applies to each block within the try…catch block. If a variable is declared within the try portion, it won’t be accessible from the catch of the finally block.

If you want to have access in those blocks, the variables need to be declared outside the try block.

The following code prevent syntax error using try...catch...finally block:

<body>
<input type="submit" onclick="canvasError()" value="Exception Handling" /><br />
<div id="#div1"> <canvas id="myCanvas"></canvas>  </div><br />
<!--  PREVENTING SYNTAX ERROR-->
<script type="text/javascript">
    var canvasError = function () {
    var context;
    try {
        var canvas = document.getElementById("myCanvas");
        var context = canvas.getContext("2d");
        context.fillStyle = "blue";
        //THERE IS AN SYNTAX ERROR - contxt 
        contxt.arc(50, 50, 25, 0, 360);
        context.fill();
        context.strokeStyle = "red";
        context.stroke();
    }
    catch (e) {
        alert(e.message);
    }
    finally {
        //do any final logic before exiting the method
        document.getElementById("#div1").innerText = "SYNTAX ERROR IN THE CANVAS";
    }
 }
</script>
</body>

Exception Bubbles

Exceptions bubble up the call stack, a special stack in the processing environment that represents the functions currently being processed in sequential order.

The following code demonstrates this:

<body>
<input type="submit" onclick="sequentialOrder()" value="RUN THE CODE"/><br />
<div id="#div1"> <canvas id="myCanvas"></canvas>  </div><br />
<script type="text/javascript">
    var sequentialOrder = function () {
        try {
            WorkWithCanvas();
        } catch (e) {
            alert(e.message);
        }
    }
    function WorkWithCanvas() {
        var canvas = document.getElementById("myCanvas");
        var context = canvas.getContext("2d");
        contxt.arc(50, 50, 25, 0, 360);
        context.fillStyle = "blue";
        context.fill();
        context.strokeStyle = "red";
        context.stroke();
    }
</script>
</body>

Throw Statement

Throw statements are used to either raise built-in exceptions or any other customized exceptions. The customized exception can be a String, number, boolean or an object.

Throw statements can be used inside try and catch statements or they can be used inside other functions.

The following code demonstrates when using throw statement:

<body>
<input type="submit" onclick="throwException()" value="Throwing an Exception" /><br />
<div id="#div1"> <canvas id="myCanvas"></canvas>  </div><br />
<!--raising an error is also known as throwing an exception, 
    using the throw keyword: -->
<script type="text/javascript">
    var throwException = function() {
        function WorkWithCanvas() {
            try {
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
                //SYNTAX ERROR
                contxt.arc(50, 50, 25, 0, 360);
                context.fillStyle = "blue";
                context.fill();
                context.strokeStyle = "red";
                context.stroke();
            } catch (e) {
                //handle the exception as appropriate
                throw e;
            } finally {
            }
        }
    }
</script>
</body>

Custom Exceptions

More commonly when working with custom libraries, you can create custom exceptions to give users information specific to the situation that occurred.

The code below uses the Error object to create the exception:

<body>
<input type="submit" onclick="customExceptions()" value="Custom Exceptions "/><br />
<div id="#div1"> <canvas id="myCanvas"></canvas>  </div><br />
<!-- create custom exceptions to give users information specific 
     to the situation that occurred -->
<script type="text/javascript">
    var ball = {
        x: -1,
        y: -1,
        draw: function DrawBall(c) {
            if (this.x < 0)
                /*The Error object constructor takes two parameters: 
                    1. the error number 
                    2. an error description*/
                throw new Error(25, "Invalid X coordinate");
        }
    }
    var customExceptions = function () {
        try {
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            ball.draw(context);
        } catch (e) {
            alert(e.message);
        }
    }
</script>
</body>

Checking for null values

One way to prevent many errors is to check for null values before using something. A null value in a JavaScript program is what a variable equals before it’s initialized.

In the following code the developer forgot to initialize a variable:

<body>
<input type="submit" onclick="checkingNullValue()" value="CHECKING-NULL VALUE" /><br />
<!--  PREVENTING NULL VALUE -->
<script type="text/javascript">
    var checkingNullValue = function () {
        try {
            //forgot to initialize th c variable
            var a, b, c;
            a = 5;
            b = 10;
            var result = multiplyNumbers(a, b, c);
            alert(result);
        } catch (e) {
            alert(e.message);
        }
    }
    function multiplyNumbers(first, second, third) {
        if (first == null || second == null || third == null) {
            throw new Error(5, "Forgot to initialize a number.");
        }
        return first * second * third;
    }
</script>
</body>

The onerror() Method

The onerror() method is an event handler fired whenever an exception occurs on the page. It is declared as a function through out the code.

This event handler provides three pieces of information:

  • An error message
  • The file in which the error occurred
  • The line number in the code

The information can be manipulated to be displayed in any way that you like.

The following code demonstrates the onerror() method:

<body>
<form>
    <input type="button" onclick="myFunc()" value="WINDOWS.ONERROR" />
</form>
<script type="text/javascript">
        //USE MOXILLA TO RUN THE CODE
        window.onerror = function (msg, url, line) {
            alert( " Message : " + msg );
            alert(" Url : " + url );
            alert( " Line : " + line );
  }
</script>
</body>

PROMOTIONS