I have a question regarding exceptions in a medium-sized Java web application.
There is a data access layer implemented using JDBC with the logic concentrated mostly in a servlet (the UI is JSP). What is a conventional exceptions’ hierarchy for applications like this?
Should I catch the exceptions on data access layer and rethrow another exception for the whole (e.g. DataAccessException) or simply let the highest level handle them (servlet).
Additionally, I have a connection pool that is called within data access layer and it has its own type of exceptions. Should these exceptions be caught inside data access layer and be rethrown as DataAccessException, or should be handled by higher levels directly?
Would it be a good idea to have a main application exception with the 2 children: LogicException and TechnicalException. Logic will have the subclasses similar to AuthentificationFailedException and so on, while the TechnicalExceptions will be responsible for conveying the information about failures like a data access layer exception, FileNotFound (while it should be) and so on?
Thank you!
Generally I wrap lower level exceptions with higher level, more meaningful exceptions. This is usually more work, but gives you decoupling between layers.
Imagine I am writing a configuration subsystem that happens to read from database. If I don’t wrap, I would have something like:
If I do the wrapping, I would have
This is definitely more work. The advantage is that if at a later time I want to change my configuration backend to, say, a file based one, without wrappers my method would become
And then I would have to change all my client code to deal with
IOExceptions instead ofSQLExceptions. If you do the wrapping, you just need to change the backend, because your client code was already written withConfigurationExceptions and its subclasses in mind. Note that this is independent of wether you use checked or unchecked exceptions: if you want to do exception handling, you almost always need to know at least some approximation for the type of exceptions you want to handle.Now, this is what I tend to do. There is people that thinks that most exceptions cannot be properly handled anyway and all these wrapping is nonsense most of the time.