Rocky Inde Rocky Inde - 1 year ago 109
Java Question

design pattern for exception handling in database layer

My system has 2 main layers, the service layer and the database access layer.

I expose an interface to the service layer for the database operations.

Now, in this interface there are a few exceptions that can get thrown by every operation of the DAO layer for example, timeout exceptions etc-

Is there a way to express this specification other than explicitly specifying for every method with

throws ExceptionName

Answer Source

There are various a lot of options here; but I think my "opinion" somehow matches up with the "best practices" that you will find in many places by now:

  • If you want to use checked exceptions, then create some abstract base exception and put that one on your throws list. Because you really do not want more than one, two exceptions on your throws list. Simply because such extensive throw lists grow over time, and they quickly pollute all your layers.
  • You can also go for not using checked exceptions! Instead: throw appropriate runtime exceptions, and document that fact via javadoc on your interfaces. Many people argue that the "war" between checked and unchecked exceptions is over, and that unchecked won. Because you need some "generic everything catching" thing on top anyway.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download