Currently we plan to have custom exceptions for business related exception cases(extending runtime exceptions)used inside a typical 3-tier architecture. So accordingly we have a data access layer, service layer and a facade layer. Basically exceptions will be caught, wrapped and propagated to the layers downstream. So the data Access layer in case of any business exception scenario will raise DataAccessException. The Service layer which calls the DAO layer will catch the DataAccessException , transform it to a ServiceException and rethrow it to the Facade layer. Here the DataAccessException and ServiceException extend javaRuntimeException. Now in the methods of the data access layer and service layer depending on business case scenario we raise the exception (throw new DataAccessException or say throw new ServiceException). The methods throwing the aforementioned exception declare the same as part of their method signature though for Runtime Exceptions we are not required to declare as part of the method signature. My question is it a good idea to throw and declare a business exception though it is a java runtime exception and not a java checked exception.
I mean technically we can do it but I want to know your thoughts on this approach which typically is applied only in case of checked exceptions. Or should we go and change our business related exception scenarios from unchecked runtime exceptions to checked exceptions.
I would change them to checked so that you are required to handle them. It would be easy to just call the DAO method and forget to catch the runtime exception in the service layer and have it fly all the way back to the browser. In my opinion RuntimeExceptions are for dealing with programming errors, say if a method parameter was null or similar. In your case I assume they are business exceptions caused by either incorrect data, DB problems etc so you should define them as checked. If you are going to catch them anyway, my not make them checked and enforce the catching rather than hoping all the developers remember?
Agree with Tom Jackson. You try to create one Exception class which directly extends Exception (so they are all checked type) then make all your other Exceptions subclasses (directly or indirectly) of that one class. That can make your catch blocks much easier to write.
Joined: Oct 23, 2003
Thanks for the feedback, Tom.
The reason I stuck to Runtime exception was due to the assumption that all business scenario related exception scenarios should be RuntimeException. Well never dug into the reason for the same.
Yes the business scenarios we are trying to tackle is something like no data found.
Joined: Oct 13, 2005
No data found probably doesn't merit an Exception; it can be regarded as a "normal" occurrence. If you are reading from a database you get a ResultSet and you can use its next() method to find whether it has any members at all.