Which exception should I throw when a static factory method fails to initialize a new object? I prefer raising a meaningful exception rather than returning null.
-
1It would depend on what caused the failure itself, i.e. a network problem, a file read failure, etc..Viruzzo– Viruzzo2012-03-13 13:05:36 +00:00Commented Mar 13, 2012 at 13:05
-
1You mean I should just throw whatever exception I got during initialization?Adam Matan– Adam Matan2012-03-13 13:06:21 +00:00Commented Mar 13, 2012 at 13:06
-
Not necessarily, but your exception should be meaningful in telling what went wrong, not just that something went wrong.Viruzzo– Viruzzo2012-03-13 13:08:04 +00:00Commented Mar 13, 2012 at 13:08
5 Answers
If you are throwing an exception in a Factory due to insufficient data, I like to throw an IllegalStateException with a description similar to "cannot construct X, no Y has been set".
If you are throwing an exception in a Factory due to conflicting data, I like to throw an
IllegalStateException with a description similar to "cannot construct X, Y conflicts with Z".
If you are throwing an exception in a Factory due to a bad (or nonsensical) value, I like to throw an IllegalArgumentException with a description similar to "Y cannot be A".
If you are throwing an exception in a Factory due to a missing value, I like to throw an IllegalArgumentException with a description similar to "Y cannot be null".
The last preference is up to some debate. Some people suggest that it might be better to throw a NullPointerException; in my case, we avoid them at all costs since many customers tend to not read the exception message (and assume that NullPointerException means a coding error).
In any event, you should provide a good, specific, message as to why the exception was thrown, to ease your future support costs of seeing that exception raised a few months from now.
Comments
You can create your own Exception by extending Exception class
3 Comments
Yeah, the cause of the problem is your best bet. If the arguments are not OK, you can throw IllegalArgumentException, if some file is not there, you can throw FileNotFoundException, if the factory is not initialized properly, you can throw IllegalStateException, etc., etc...
However, creating your own Exception is easy. Just declare you class as extends Exception and add delegate constructors. If you extend Exception, then that method which can throw it must be declared with throws. If you don't want that, you can extend RuntimeException, those need not be declared.