Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Art of Java: Chapter 13 exception handling

 
Junilu Lacar
Bartender
Posts: 7465
50
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Neil. Welcome to JavaRanch!
I had a look at one of the sample chapters from the book, Chapter 13. In the section about exceptions you talk about the differences between technical exceptions (e.g. SQLException), domain exceptions, and RuntimeException. In Listing 13.28, SQLException is caught, wrapped and rethrown as a RuntimeException. A recent OnJava.com article by Gunjan Doshi also recommends this practice. Doshi explains that you shouldn't hesitate to do so because there is generally nothing that client code can do about SQLException anyway. I am a bit ambivalent about this advice though because a SQLException does not necessarily indicate that something is wrong with the code and I would generally forward to a "having technical difficulties" type error page.
What are your thoughts?
 
Neal Ford
Author
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu -
In Listing 13.28, SQLException is caught, wrapped and rethrown as a RuntimeException. A recent OnJava.com article by Gunjan Doshi also recommends this practice.

I do this sometimes, but I don't think I would universally recommend it. The checked exception mechanism in Java is a good one -- though sometimes inconvenient. Errors tend to be inconvenient, both for developer and user. Generally, I will catch the exception and try to handle it, by logging, forwarding to an error page, or something else.
A lot of Java developers like to short-circuit checked exceptions, wrapping them all in RuntimeException (as I've shown here). It isn't a war crime, but I think it discards a very useful language feature. After all, if I were opposed, I wouldn't have shown it! However, most of the code in the book handles exceptions more traditionally.
 
Chris Mathews
Ranch Hand
Posts: 2712
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't like to wrap with a generic RuntimeException though I do frequently wrap any exception coming out of the persistence tier with a custom PersistenceException which extends from RuntimeException. This gives me the benefit of unchecked exceptions coupled with the ability to easily handle all persistence related exceptions in a catch block (otherwise I would be catching RuntimeException which I don't typically like to do). JDO works in a very similar with all exceptions extending a base JDOException which is unchecked. I personally like this a lot but YMMV.
[ February 10, 2004: Message edited by: Chris Mathews ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic