Although I think I have some knowledge of application design principles, it’s something I’d like to improve on, especially in the area of JavaScript and Ajax-driven applications.
One technique that I believe is quite helpful when developing high-powered JavaScript apps is the JavaScript try-catch
statement (also referred to as try-catch-finally
). I became familiar with try-catch
sometime last year, and although I haven’t used it much, I found it could prove useful in a number of circumstances.
In this article, I’m going to describe what try-catch
is, how it can be used, and how it can help make web applications less annoying to users.
Basic Syntax and Definition
The try-catch
statement was introduced in ECMA-262, 3rd Edition as a way to handle exceptions, and its syntax is the same as in the Java programming language. Here is how a basic try-catch
statement looks:
try { // code that might cause an error goes here } catch (error) { // error message or other response goes here }
The try
portion is where you would put any code that might throw an error. In other words, all significant code should go in the try
section. The catch
section will also hold code, but that section is not vital to the running of the application. So, if you removed the try-catch
statement altogether, the section of code inside the try
part would still be the same, but all the code inside the catch
would be removed.
If any error occurs during the try
portion, the try
section is exited and the catch
section is executed. The catch
portion of the statement will receive a JavaScript object containing error information. The error
identifier is required, but can be any custom name you choose. For example, the following would be the same as the previous code example:
try { // code that might cause an error goes here } catch (watermelon) { // error message or other response goes here }
In the above example, the “error” identifier has been changed to “watermelon”, but will have the same results. Obviously, a name like “watermelon” would be counterproductive, but this simply serves to demonstrate that the name is flexible, but is required.
Outputting the Exact Error That Occurred
The error
object (or watermelon
object, depending on what you named it), has a property called message
that holds details about the error that occured. So, the following would be a practical way to output a custom error:
try { doSomething(); // this function doesn't exist } catch (error) { alert(error.message); }
If you run the code above, the browser will alert the message “doSomething is not defined”. The error object also defines a property called name
that describes the error in a more technical fashion, but I don’t really see any practical use for it. Those two properties are the only ones that are cross-browser compatible. Different browsers offer custom properties, some of which could prove useful, such as lineNumber
in Firefox. But generally, it’s best to stick to using just the message
property, since it’s the most compatible and practical one available.
The Optional “finally” Clause
The try-catch
statement also permits the inclusion of a finally
clause. The code inside the finally
section will run no matter what. This comes in handy because that is not true of the try
section. For debugging purposes (or other reasons) you may require a certain section of code to execute, even if errors occur. Such code should be placed in the finally
section. There is nothing that could occur in the try
section or in the catch
section that would prevent the finally
section from executing. Even if a different return
statement is placed in each section, only the last return
statement (the one in the finally
section) will actually “return”.
Look at the following example:
function testReturn() { try { return "bananas"; } catch (error) { return "oranges"; } finally { return "watermelons"; } } alert(testReturn());
Although it seems the alert
message should say “bananas” (because there is no error), it will actually output “watermelons”, because the finally
clause always executes, regardless of any errors. Of course, this only happens because of the nature of the return
statement. The try
section would still execute, but the return
of the try
would be overriden by the return of the finally
clause.
Here is the same code, slightly modified:
function testReturn() { try { alert("bananas"); } catch (error) { return "oranges"; } finally { return "watermelons"; } } alert(testReturn());
Now the output will be two alert
statements. The first one is “bananas”, the second is “watermelons”. To prevent any problems resulting from overridden return
statements, make sure your try
and finally
clauses don’t both contain return
statements, otherwise only the finally
return will actually be “returned”.
When Should You Use try-catch
?
The try-catch
statement should be used any time you want to hide errors from the user, or any time you want to produce custom errors for your users’ benefit. If you haven’t figured it out yet, when you execute a try-catch
statement, the browser’s usual error handling mechanism will be disabled.
You can probably see the possible benefits to this when building large applications. Debugging every possible circumstance in any application’s flow is often time consuming, and many possibilities could be inadvertantly overlooked. Of course, with proper bug testing, no area should be overlooked. But the try-catch
statement works as a nice fallback in areas of your code that could fail under unusual circumstances that were not foreseen during development.
Another benefit provided by the try-catch
statement is that it hides overly-technical error messages from users who wouldn’t understand them anyhow.
The best time to use try-catch
is in portions of your code where you suspect errors will occur that are beyond your control, for whatever reasons.
When Should try-catch
be Avoided?
You shouldn’t use the try-catch
statement if you know an error is going to occur, because in this case you would want to debug the problem, not mask it. The try-catch
statement should be executed only on sections of code where you suspect errors might occur, and due to the overwhelming number of possible circumstances, you cannot completely verify if an error will take place, or when it will do so. In the latter case, it would be appropriate to use try-catch
.
Are There Performance Issues with try-catch
?
The short answer seems to be yes, although this article on MSDN says that performance is affected only when the catch
portion actually executes. This response to that article suggests otherwise.
An article on the Opera Developer Community says that try-catch-finally
should be avoided inside performance critical functions.
Finally, there is a good, but limited, bit of info on try-catch
in relation to performance, in Nicholas Zakas’ new book, High Performance JavaScript.
I can’t say for certain which view is correct, but as long as you use it in the most appropriate circumstances, performance hits will likely be kept to a minimum.
Overall, try-catch
is a useful statement and can come in handy in a number of circumstances — especially when creating large applications that could potentially create situations that are beyond a developer’s control.
Good write up, I’ve been studying a lot of PHP as of late and the try-catch functions are just about the same. Very good and easy description of it in JavaScript, thanks.
Nice tutorial! Simple and very effective. I didn’t knew that try-catch had some performance issues, good to know…
I believe this could be a great tutorial for newbies.
Nice article, try-catch definitely helped me in lot of my development. Expecting more good articles
Thomas Fuchs demonstrated the try-catch function to be ressources hungry : http://mir.aculo.us/2009/12/24/extreme-javascript-performance-video/
Thanks, Lars, I’ll check that out when I get a chance.
its a very informative post. thanks.
This is a great tutorial. Everything makes sense and works great! Thanks for sharing.
Make sense, but I am little confuse whether we go for it or not. I am using angular.js and just wanted to ask shall I put try catch or not please share your suggestions.