How to Handle Passing a DAO Object with Custom Exceptions in Java

exceptionsjavamaven

I have my multi module maven project with the following structure:

+ parent
   - pom.xml

+ model
   - persistents
   - dao
   - model stuff...
   - pom.xml

+ service
   - services
   - services stuff...
   - pom.xml

+ utils
   - exceptions
   - pom.xml

In utils module I have some custom exceptions.
The point is that, in my exceptions I want to have the change to to give the object that caused the exception, for example, let's suppose we have the persistent class User. The userDao throws an UserNotFoundException. I want to have the following constructors:

UserNotFoundException(String message)

UserNotFoundException(String message, User user)

The idea is to be able to have the object that caused the exception when handling it. However, it sounds so strange to me throwing the persistent object inside an exception… Is that correct? Does it make sense throwing the object in a exception? (I think it could be usefull to see how the object is when the exception appears).

Best Answer

The question is: what can you do with that object at the point where you catch the exception?

All cases I have seen in the wild the exception is logged or shown to the user. In that scenario there is no use for the real object other than calling its toString() method. Even worse: You want to get some other property to be included in the message depending on the root cause of the exception? How do you know that in the catch block? But at the place where the exception is thrown you know very well which property of the object might be of interest...

So as usual my Answer is: it depends.

The fact that I cannot think of something useful to do the object within the catch block does not mean that you can't either...

But unless you experienced that need you should not force anyone else to follow your pattern.

Related Topic