I don't consider myself an application developer. I think I have someknowledge of application design principles, but it's something I'd liketo improve on, especially in the area of JavaScript and Ajax-drivenapplications. 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 DefinitionThe 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 erroridentifier is required, but can be any custom name you choose. Forexample, 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 todemonstrate that the name is flexible, but is required. Outputting the Exact Error That OccurredThe 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 propertycalled name that describes the error in a more technicalfashion, but I don't really see any practical use for it. Those twoproperties are the only ones that are cross-browser compatible.Different browsers offer custom properties, some of which could proveuseful, 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" ClauseThe 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 trysection. For debugging purposes (or other reasons) you may require acertain section of code to execute, even if errors occur. Such codeshould 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 youwant to hide errors from the user, or any time you want to producecustom errors for your users' benefit. If you haven't figured it outyet, 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 buildinglarge applications. Debugging every possible circumstance in anyapplication's flow is often time consuming, and many possibilitiescould be inadvertantly overlooked. Of course, with proper bug testing,no area should be overlooked. But the try-catch statementworks as a nice fallback in areas of your code that could fail underunusual 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-catchstatement should be executed only on sections of code where you suspecterrors might occur, and due to the overwhelming number of possiblecircumstances, you cannot completely verify if an error will takeplace, or when it will do so. In the latter case, it would beappropriate 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 youuse it in the most appropriate circumstances, performance hits willlikely be kept to a minimum. Overall, try-catch is a useful statement and can comein handy in a number of circumstances - especially when creating largeapplications that could potentially create situations that are beyond adeveloper's control. Source: http://www.impressivewebs.com/javascript-try-catch/ |