{"id":255,"date":"2007-11-25T20:54:00","date_gmt":"2007-11-26T01:54:00","guid":{"rendered":"http:\/\/unitstep.net\/blog\/2007\/11\/25\/exception-handling-in-javascript\/"},"modified":"2008-01-30T20:32:26","modified_gmt":"2008-01-31T01:32:26","slug":"exception-handling-in-javascript","status":"publish","type":"post","link":"https:\/\/unitstep.net\/blog\/2007\/11\/25\/exception-handling-in-javascript\/","title":{"rendered":"Exception handling in JavaScript"},"content":{"rendered":"
Exception handling is a topic that may not be well-understood by some web developers, depending on what languages they have the most experience in. In particular, PHP<\/acronym>, one of the most common server-side languages for web development, did not have support for exception handling until version 5<\/a>. In the four years between the release of PHP4 and PHP5, the language became increasingly popular among developers, and as a result, a lot of code was written without exception handling in mind. The situation did not even improve much with the release of PHP5, since PHP5 was meant to be backwards-compatible with code developed for PHP4. Three years later, there are still movements<\/a> to get developers to transition to a purely-PHP5 model.<\/p>\n Some of this may have transferred over to JavaScript, a language that is already poorly understood and often implemented even worse. It is often hard to find well-written, maintainable JavaScript code, as it is often left as an afterthought in a project or otherwise not given much consideration, having been delegated to the realm of popup scripts and mouse-overs. While exception handling may be overkill for a lot of JavaScript applications, many do not even know of JavaScript’s exception-handling capabilities. In this article, I’ll give a brief overview of exception handling and some recommendations on how to use it in JavaScript to improve the readability of code. <\/p>\n <\/p>\n I won’t go too in-depth about the merits of using exception handling<\/a> but will instead just give a brief overview. (While there are some drawbacks, these apply more to the Java language rather than JavaScript)<\/p>\n The main reason for using exceptions is to have a separate channel for communicating errors. Without this, you must communicate error conditions using the function itself. Consider a function that performs mathematical division:<\/p>\n Division is a fairly simple arithmetic operation, but of the four basic operations it is the only one that has limits on its arguments: the divisor (the term you divide by) cannot be zero, since division by zero is undefined.<\/a> So, how should you handle cases where the supplied arguments result in division by zero? (The situation is very likely in an application accepting user input)<\/p>\n Without using exceptions, you have a few options, each of which has its own weaknesses. Firstly, you could choose not to return anything<\/em> and just Secondly, you could choose to return a special “error code” indicating that there was a division by zero. But this creates another problem – what exactly do<\/em> you return when something goes wrong? In this case, the only error case is division by zero – since JavaScript is a weakly-typed language, you could just return Alternatively, you could just check the inputs\/arguments every time before you called the function. However this is clumsy, and adds another layer of complexity where something could go wrong. <\/p>\n As mentioned before, exception handling adds a side channel of sorts strictly for communicating errors. By doing this, it allows for the interruption of program flow for the purpose of dealing with the exception or error situation. Using exceptions, you would re-write the function above like this:<\/p>\n Here we are checking if the divisor equals zero – signifying an invalid input value – and then throwing an exception if this is the case. How is this different than returning an error code?<\/p>\n The main difference is in the control flow<\/em> of the program; using exceptions causes a change in the program flow. In the above example, if the divisor equals zero, the execution of the function stops there and returns to the calling code with the throw exception. The subsequent statements calculating the quotient and returning will not be executed. Here’s an example of how you’d call the With exceptions, you enclose code that could throw an exception with a In this example, everything works until the line calling If, however, you executed the code with valid values and no exceptions were thrown, once the program had got to the end of the Since Java is an extremely popular language and one that also uses a similar exception handling model, it would be prudent to discuss some of the differences and similarities with it and JavaScript.<\/p>\n It appears I was mistaken. In JavaScript, you can indeed have multiple catch blocks<\/a>, as seen in the Core JavaScript 1.5 Guide<\/a> from the Mozilla Developer Center. My initial example above is still valid syntactically, but this way may be more appealing. An example is as follows:<\/p>\n It just goes to show that when you think you know something, you probably don’t! This is part of why I like JavaScript (and by extension, programming); there’s always more to learn and experience to be gained.<\/p>\n<\/li>\n The discussion of exception types brings us to another point – the different exception types in JavaScript. JavaScript defines some built-in exception<\/a> types, all based off the parent In that situation, things get a little tricky, especially if you’re coming from Java. Despite the outward similarity, JavaScript does not uses classes like Java, but instead uses a prototype-based approach<\/a> where inheritance comes from existing objects. In this respect, things can get complicated as there are debates on what the best way to inherit from objects<\/a> is and to that degree, a few JavaScript libraries have been written to facilitate the extending of objects in JavaScript. These points are beyond the scope of this article, but I thought I’d just point you in the right direction.<\/p>\nExceptional conditions<\/h2>\n
function divide(dividend, divisor)\r\n{\r\n var quotient = dividend\/divisor;\r\n return quotient;\r\n}<\/code><\/pre>\n
alert()<\/code> the user of the error. This isn’t good since when you call the
divide()<\/code> function, you expect a result, not a warning message.<\/p>\n
false<\/code> on this error, but then in the calling code you’d have to check if
divide()<\/code> equaled
false<\/code> before using it, probably using the strict equality operator<\/a>. As you can see, things get messy fast. <\/p>\n
Another way of doing things<\/h2>\n
function divide(dividend, divisor)\r\n{\r\n if (0 == divisor) {\r\n throw new Error(\"Bzlorg! Cannot divide by zero.\");\r\n }\r\n \r\n var quotient = dividend\/divisor;\r\n return quotient;\r\n}<\/code><\/pre>\n
divide<\/code> function.<\/p>\n
try {\r\n var dividend = 3;\r\n var divisor = 0;\r\n \r\n var quotient = divide(dividend, divisor);\r\n\r\n alert(\"The answer is \" + quotient);\r\n}\r\ncatch (e) {\r\n alert(e.message);\r\n}<\/code><\/pre>\n
try<\/code> block. This signifies to the interpreter (in the case of JavaScript) that you will be executing code (in this case, calling a function) that could<\/em> throw an exception as a result of some error condition. Thus you are
try<\/code>ing to do something – but as in real life, things may go wrong.<\/p>\n
divide<\/code>. Since
divide<\/code> throws an exception with the input values supplied, flow will be directed to the
catch<\/code> block. All
try<\/code> blocks must be followed with a
catch<\/code> block, with the variable in the parentheses specifying the variable to hold the thrown exception object. In the code above, we merely alert the user to the problem – the message “Bzlorg! Cannot divide by zero” is displayed – in a real program you most likely would want to do handle the error differently depending on the context – but that’s a whole different topic.<\/p>\n
try<\/code> block it would jump over the following
catch<\/code> block and the user would be alerted with the correct answer. Code within a
catch<\/code> block is only<\/em> executed in the event that an exception is thrown.<\/p>\n
Differences with Java<\/h3>\n
\n
No multiple catch blocks with JavaScript<\/del><\/h4>\nThis is perhaps the biggest difference. If you’re familiar with Java you’ll know that different exception objects can be thrown during execution (all subclasses of the root\/parent Exception<\/code> class defined by Java), each signifying different error conditions. You catch each of them separately by using separate catch blocks, each specifying a particular class or parent class. However, with JavaScript, as you might have noticed from the code above, there can only be one catch block and thus there’s no need to specify the exception class. <\/del><\/p>\n
If, however, you want the granularity of working with different exception classes, you’ll have to use the instanceof<\/code> operator within a catch block, like this:<\/del><\/p>\n
try {\r\n ...\r\n}\r\ncatch (e) {\r\n if (e instanceof RangeError) {\r\n ...\r\n }\r\n else if (e instanceof TypeError) {\r\n ...\r\n }\r\n}<\/code><\/pre>\n
It’s not as elegant as having multiple catch blocks, but it’s one way to deal with multiple exception types.<\/del><\/p>\nCorrection:<\/h4>\n
try {\r\n ...\r\n}\r\ncatch (e if e instanceof RangeError) {\r\n ...\r\n}\r\ncatch (e if e instanceof TypeError) {\r\n ...\r\n}\r\ncatch (e) {\r\n \/\/ General catch-all block.\r\n ...\r\n}<\/code><\/pre>\n
Exception types<\/h4>\n
Error<\/code> object. These should suffice for most situations where you’re checking user input (the most common use), but if you’re developing a complex application you may want to define your own. <\/p>\n