I am wondering what to do with unexpected exceptions that occur in my business layer. What do you guys think is the best approach?
The reason I am unsure is because if these particular problems occur it implies that something serious has gone wrong with the system.
My particular problem is within the book-method of my Business Service class. When I am about to book a room I first lock the record in the database. Then I read the record back from the database to ensure that it is still unbooked before continuing.
Now, the read method on my database throws a RecordNotFoundException. In theory this should never get thrown when I am reading back the record as I already own the lock, so no one should have been able to delete the record. My code is like this:
So, if a RecordNotFoundException is thrown when I read the record after locking it, then something seriously wrong has happened in the system. But what should I do with the exception when I catch it here in my Business Layer?
My initial thoughts were to simply thrown an IllegalStateException. But this is a runtime exception and my client code will not be set up to handle this - I will just end up with an exception being thrown in the console probably.
Another thought I had was to just throw a general BusinessException to indicate that something has gone wrong. I already have this exception class in my code. When the client code receives this exception it just tells the user that "Something unexpected has gone wrong when attempting to book the room, please try again". But would that really be the correct message to send to the user in this particular scenario?
I throw an IllegalStateException and documented this should never occur
But in my case, code-which-can-throw-IllegalStateException is inside lock method, which can only throw RNFE (interface restrictions). Should I swallow the IllegalStateException? What can be done in such case?
As a SCJP you should know that an interface only restricts the checked exceptions being thrown, but that you can throw any runtime exception you want. And the IllegalStateException is a runtime exception.
That's true. But you should not forget to run the application with assertions enabled, otherwise you won't notice you have a bug in your code. So if you use assertions throughout your code that won't be a problem. But if you use only assertions in this case, you might forget it and never notice you have written a bug.