10.2 Performance Impact of Exception Handling


In general, wrapping your Java code with try/catch blocks doesn't have a significant performance impact on your applications. Only when exceptions actually occur is there a negative performance impact, which is due to the lookup the JVM must perform to locate the proper handler for the exception. If the catch block for the exception is located in the same method, the impact is not so bad. However, the further down the call stack the JVM has to go to find the exception handler, the greater the impact becomes.

This is why you should use a try/catch block only for error conditions. You should never use exceptions for things such as controlling program flow. The following use of a try/catch block is probably fine, but it's getting very close to improper use of exception handling:

Double basePrice = null; String basePriceStr = request.getParameter( "BASE_PRICE_AMOUNT" );       // Use a try/catch to make sure the value is a number try{   basePrice = Double.valueOf( basePriceStr ); }catch( NumberFormatException ex ){   // The value could not be converted to a valid Double; set the default   basePrice = ApplicationDefaults.DEFAULT_BASE_PRICE; }

The previous code fragment shows a try/catch block determining an error condition and taking corrective action. The error condition is an invalid price value, and the corrective action is to assign a default value. There are other ways to determine whether a string is a valid Double value, but using this approach is fairly popular. Fortunately, the exception handler is located in the same method, and the JVM doesn't incur a large penalty for this occurrence.

Of course, rules are always somewhat subjective, and what is a valid reason to one developer may not be to another. You should be aware of the drawbacks and avoid using try/catch blocks other than for actual error conditions.



Programming Jakarta Struts
Programming Jakarta Struts, 2nd Edition
ISBN: 0596006519
EAN: 2147483647
Year: 2003
Pages: 180

Similar book on Amazon

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