Newsletter sign-up
View all newsletters

Sign up for our Enterprise Java Newsletter

Enterprise Java

Use exceptions with care

The JavaWorld experts answer your most pressing Java questions -- every week

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone

QPlease explain the following sentence: 'Use exceptions where you really need them -- not only do they have high basic cost, but their presence can hurt compiler analysis.'

A Just as it can be more difficult for people to read code that has try-catch blocks, it is more difficult for a compiler to analyze such code. In terms of legibility, however, try-catch blocks can actually be beneficial, because they describe the types of problem situations the software is expected to manage and how it is expected to manage them. This mechanism allows you to deal with problems as close to their source as you choose. At runtime, the presence of try-catch blocks doesn't significantly affect performance -- except when an exception occurs. In such situations, however, you must handle the exception anyway, so the cost is tolerable.

Only when the situation is truly exceptional should you use this mechanism, though you may be tempted to throw exceptions simply to take advantage of their control-flow aspects. A good use of this mechanism would be to throw an exception if a file could not be found; a poor use would be to throw an exception with the name of a file that had been found. In the former case, the cost of the mechanism would only be incurred when the app was unable to proceed normally; in the latter case the cost would be incurred all the time without any added benefit.

About the author

Random Walk Computing is the largest Java/CORBA consulting boutique in New York, focusing on solutions for the financial enterprise. Known for their leading-edge Java expertise, Random Walk consultants publish and speak about Java in some of the most respected forums in the world.
  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Comment
Login
Forgot your account info?
Add comment
Anonymous comments subject to approval. Register here for member benefits.
Have a JavaWorld account? Log in here. Register now for a free account.
Resources