Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Java Tip 134: When catching exceptions, don't cast your net too wide

Understand how Java compilers check catch clauses at compile time

  • Print
  • Feedback

Page 3 of 3

Sometimes, catching Exception makes sense, such as in your application's last-ditch error handler or in the execution engine of an application server where you don't want a coding error in one service to bring down the whole server. But most code doesn't need this special treatment. Think twice!

Note that IBM's Java compiler, Jikes, does warn you about catching Throwable or Exception without explicitly throwing them—as well as many other items not caught by Sun's compiler. However, it doesn't warn about catching an exception superclass when only a subclass is thrown. I don't have enough experience with Jikes to recommend using it routinely, but it's easy to try, and I certainly recommend checking it out if you're interested.

Best practices

To sum up, Java allows you to lose error-handling information when you catch an exception: you can catch a superclass instead and lose the specific information conveyed by the subclass. If you catch Exception or Throwable, you won't even be told if your code doesn't throw an exception at all. So, how to stay out of trouble?

  • Catch the most specific exception that you can. Catch a superclass only if you're certain that all the exceptions you'll catch by doing so have the same meaning to your code—and consider what new subclasses future versions of a method might want to throw too. Never catch Exception or Throwable if you can help it.
  • If you're forced to catch Exception or Throwable, consider handling RuntimeException or Error separately from other Exception or Throwable subclasses. And follow the golden rule: never throw Exception or Throwable yourself.
  • As you refactor evolving code, watch for situations where removing code removes possibilities for exceptions to be thrown—the compiler won't always tell you.


With these guidelines in mind, you'll be better prepared to write even more exceptional code.

About the author

Dave Schweisguth has written software in the biotechnology industry since 1996 and used Java since 1997. Presently he's a software architect for Applied Biosystems in Foster City, Calif., where he contributes to and evangelizes the company's next-generation service-oriented software architecture.

Read more about Tools & Methods in JavaWorld's Tools & Methods section.

  • Print
  • Feedback

Resources