Handling Exceptions

Handling Exceptions

JavaScript supports a familiar type of exception handling for C# developers. Code can throw an exception. If located inside a try block, a corresponding catch block can handle the exception. After that, a finally block will execute to take care of any necessary cleanup or global recovery approach. The try-catch-finally pattern is important in being able to write robust code that can recover from error conditions.

The Java runtime environment (not JavaScript) requires that code declare up front any type of exception that it may want to catch. When it is compiled, the type of exceptions that may be thrown are checked. You must explicitly catch all of the possible exception types. The .NET Framework does not require declaring what type of exception a method may throw. You can catch the base-exception type and then deal with more specific exception types as you see fit. You can even define custom exception types derived from existing types for greater specialization. In JavaScript, there are no static checks on types of exceptions. You simply catch the exception, which has a base type of object, and react as you see fit. It is not uncommon to have exception-handling code that looks at the details of the exception thrown to determine what the course of action should be. In many situations, throwing a basic Exception using a string constructor is adequate to signal what recovery action is necessary. This choice is entirely a runtime determination. Listing 3-18 (Exceptions.aspx) shows a set of try-catch-finally blocks. The runtime overhead and complexity associated with exception-handling semantics in other languages is not the same in JavaScript. If your preference is to use exceptions as part of flow control, you need not worry about a significant impact on performance.

Listing 3-18
Image from book

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Exceptions</title>
<script type="text/javascript">
<script type="text/javascript ">
try {
    var now = new Date().getTime();
    if ((now % 2) === 0) {
        throw "even ticks";
    }
    else {
        throw "odd ticks";
    }
}
catch (ex) {
    if(ex === "even ticks") {
        document.write("an even exception occurred <br />");
    }
    else if (ex === "odd ticks") {
        document.write("an odd exception occured <br />");
    }
    else {
        alert(ex);
        document.write("a mathematical anomaly occured");
    }
}
finally {
    document.write("all done");
}
</script>

</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>
Image from book