In my company we are building a webapp containing serveral central services that we design ourselves and then specify as interfaces. I.e. the interfaces are application specific and they are then implemented with third party libraries which we may change over time. When it comes to exceptions, I have realized that the exceptions thrown by our services should be our own application-specific exceptions as opposed to implementation specific exceptions.
Now, I am wondering how our exceptions should be structured and related to each other.
First, consider a generic exception
MyAppException. This exception indicates that something unexcpected went wrong and the best thing we can do is to display a message to the user saying that something went wrong and that we are working on it. The error could be that the database crashed or something similair. This exception would pretty much be thrown from all methods working with the database.
Secondly, consider an exception
MyAppDuplicateException. This exception would indicate that the user tried to save something into the database that was already there. Here, we can display a much more specific error message and this exception is only thrown from the methods that inserts or updates database rows.
The application can also contain other exceptions similar to
MyAppDuplicateException for other excpected error situations. Ex
Now to my questions:
- Should the other exceptions extend
MyAppException? I actually see no reason for this, I have just seen it in a lot of places and wonder if there is a purpose to it. The downside of this as I see it is that a try/catch-statement does not need to care about the specific exception in this case. It can just catch the top exception and because of this it does not need to handle the specific error which was pretty much the point of having the specific exception.
- If the other exceptions does not extend
java.lang.RuntimeException? This would not require executing code to catch it, which to me sounds natural since the point of the exception is to say that something unknown happened and the executing code is not excpected to be able to handle it. The code at the entry point of the request could still have a try/catch statement that catches
MyAppExceptionand makes sure that a message is displayed to the user.
edit There is no question if the specific exceptions like
MyAppDuplicateException should be checked or not, the should defenetly be checked.