{"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

Exceptional conditions<\/h2>\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

function divide(dividend, divisor)\r\n{\r\n  var quotient = dividend\/divisor;\r\n  return quotient;\r\n}<\/code><\/pre>\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 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

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 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

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

Another way of doing things<\/h2>\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

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

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 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

With exceptions, you enclose code that could throw an exception with a 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

In this example, everything works until the line calling 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

If, however, you executed the code with valid values and no exceptions were thrown, once the program had got to the end of the 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

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

    \n
  1. \n

    No multiple catch blocks with JavaScript<\/del><\/h4>\n

    This 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>\n

    Correction:<\/h4>\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

    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

    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

  2. \n

    Exception types<\/h4>\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 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

    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>\n

    Interestingly, you can also throw many different<\/a> types of expressions, and are not limited to the built-in exception types. For example, throw false;<\/code> and throw \"Hello World\";<\/code> are valid statements, but in my opinion, it doesn’t make much sense to throw any type of expression just because you can. Using the built-in exception types (or defining your own) is a better practice, though throwing just String expressions might be alright in some situations.\n<\/li>\n

  3. \n

    Runtime errors<\/h4>\n

    During execution, you code may trigger runtime errors within JavaScript – for example, when trying to reference a property on a non-existent object. These will also result in a new Error<\/code> object being thrown, even though you did not define this throw in your code. If this happens within a try block, the exception will subsequently be caught in the following catch block, and if you’re not expecting this error you may miss it. (If, for example, you’re only looking for specific exception object types)<\/p>\n

    This can create problems with some of the JavaScript debuggers out there like Firebug<\/a>. Since the runtime exception is being caught, Firebug will not be able to catch it (it is prevented from “filtering” up), so you may not be able to locate the source of your error if you’re relying on the debugger. <\/p>\n

    My recommendation is thus to ensure your code runs properly under normal conditions. Only then should you start using exceptions and try-catch statements. This will ensure that no unexpected runtime exceptions get caught. (The runtime errors are analogous to the unchecked runtime exceptions of Java in that they are not normally caught)\n<\/li>\n<\/ol>\n

    Summing it up<\/h3>\n

    The whole point of using exceptions is not to make your code “work” better – anything that can be accomplished with exceptions can most likely be done without it, with just the same end result. The point is to make your code more readable, manageable and flexible. By using exceptions you get rid of having to use cumbersome “error codes”, the values of which you may forget later. You also get more flexibility with how you handle errors. You need not handle the error right in the function where it occurs – you can throw an exception to the calling code and handle the error there – or, alternatively, you could let the exception bubble up to a higher-level and handle all errors there. It really depends on your needs, but using exceptions allows for this to be implemented more readily.<\/p>\n

    Though exceptions may seem like overkill for JavaScript and despite the limitations of its exception handling model as compared to that of Java’s, there are still some benefits to using exceptions, especially for complex JavaScript applications that you may implement to improve the interactivity of your site. <\/p>\n

    Changes\/Fixes<\/h4>\n
      \n
    • 2007-12-06<\/strong>: Changed throw new Exception(...)<\/code> to correct statement of throw new Error(...)<\/code>.<\/li>\n
    • 2008-01-08<\/strong>: Fixed incorrect assertion of “No Multiple Catch Blocks” in JavaScript; added remarks about being able to throw any type of expression.<\/li>\n<\/ul>","protected":false},"excerpt":{"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, one of the most common server-side languages for web development, did not have support for exception handling until version 5. In the four years between the release of […]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[170,64,4,137],"tags":[],"_links":{"self":[{"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/posts\/255"}],"collection":[{"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/comments?post=255"}],"version-history":[{"count":0,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/posts\/255\/revisions"}],"wp:attachment":[{"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/media?parent=255"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/categories?post=255"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unitstep.net\/wp-json\/wp\/v2\/tags?post=255"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}