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

Get Programming Jakarta Struts, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.