Section 11.6. Advanced Error-Handling Techniques (try, throw, catch)


11.6. Advanced Error-Handling Techniques (try, throw, catch)

Calling functions and testing return values is acceptable in an application, but it isn't optimal. A better approach is to make function calls and use objects without continuously testing for results, and then include exception handling at the end of the script to catch whatever errors happen.

Beginning with JavaScript 1.5, the use of TRy...catch...finally was incorporated into the JavaScript language. The try statement delimits a block of code that's enclosed in the exception- handling mechanism. The catch statement is at the end of the block; it catches any exception and allows you to process the exception however you feel is appropriate.

The use of finally isn't required, but it is necessary if there's some operation that must be performed whether an exception occurs or not. It follows the catch statement, and, combined with the exception-handling mechanism, has the following format:

try { ... }  catch (e) { ... } finally { ... }

There are six error types implemented in JavaScript 1.5 engines:


EvalError

Raised by eval when used incorrectly


RangeError

Numeric value exceeds its range


ReferenceError

Invalid reference is used


SyntaxError

Used with invalid syntax


TypeError

Raised when variable is not the type expected


URIError

Raised when encodeURI( ) or decodeURI( ) are used incorrectly

Using instanceOf when catching the error lets you know if the error is one of these built-in types. In the following code, a TypeError is deliberately invoked, and then captured. The exception that's thrown has a message property that can be printed out to get information about the exception:

try {   var somearray = null;   alert(somearray[18]); } catch (e) {    if (e instanceof TypeError) {       alert("Type error: " + e.message);    } }

You can also use multiple tests for the type of error, log the error, and even call a special exception handlerall within the catch block. If you have any functionality that needs to be processed regardless of success or failure, you can include this in the finally:

try {   var somearray = null;   alert(somearray[18]); } catch (e) {    if (e instanceof TypeError) {       alert("Type error: " + e.message);    } } finally {    somearray = null; }

This more sophisticated form of exception handling fits in with object construction because your object methods can throw exceptions using the associated tHRow statement, rather than having to fuss around with returning null or some other failed value. You can throw any number of exception types and then process them accordingly in the code that is working with the object.

In Example 11-7, the small object library and related example from Example 11-5 is modified so that it doesn't use the parseFloat function, which ensures that the opacity settings are treated as numbers before modifying the value. In addition, the two methods that set the opacity now test to see if the value is a number, and throw an exception if not. The calling function catches this exception and prints out the message.

Example 11-7. Testing opacity settings

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Exceptions</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript"> //<![CDATA[ var div1; function alphaOpacity(value) {    if (typeof value == "number") {       var opacity = value * 100;       this.style.filter = "alpha(opacity:"+opacity+")";    } else {       throw "NotANumber";    } } function cssOpacity(value) {    if (typeof value == "number") {       this.obj.style.opacity = value;    } else {      throw "NotANumber";    } } function getOpacity(  ) {    if (this.obj.style.filter) {        return this.obj.style.filter.alpha;    } else {        return this.obj.style.opacity;    } }function changeOpacity(  ) {    try {       // div1       var currentOpacity = div1.objGetOpacity(  );       currentOpacity+=0.1;       div1.objSetOpacity(currentOpacity);    } catch (e) {       alert(e);    } } function DivObj(obj) {    this.obj = obj;    this.objGetOpacity = getOpacity;    this.objSetOpacity = obj.style.filter ? alphaOpacity : cssOpacity ; } function setup(  ) {   div = document.getElementById("div1");   div1 = new DivObj(div);   // set initial opacity   div1.objSetOpacity(0.0);   // event handlers   document.onclick=changeOpacity; } //]]> </script> </head> <body onload="setup(  )"> <div > <img src="/books/4/327/1/html/2/fig01-1.jpg" /> </div> </body> </html>

The methods that set the opacity for the object don't normally return a value; doing so just for error handling is not the way to go. Instead, by throwing the exception, the calling program doesn't have to test the status of the method return, and the methods can trigger the error handling. Of course, without having any kind of exception handling, throwing the exception and not catching it triggers a JavaScript error. Even though that is appropriate, why have exception handling only to disregard its use?

As stated at the beginning of this section, exception handling in JS is relatively new. It's a product of the ongoing effort to improve the object-oriented qualities of a language that some people call chaotic and unruly. There's a move to put some controls on this wild child of the programming languages by issuing a new major revision of JavaScript: JavaScript 2.0. This effort is discussed in this last section.




Learning JavaScript
Learning JavaScript, 2nd Edition
ISBN: 0596521871
EAN: 2147483647
Year: 2006
Pages: 151

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net