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
.
An ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable. As of release 1.4, this exception has been retrofitted to conform to the general purpose exception-chaining mechanism.
How to handle the ExceptionInInitializerError Error. To avoid this error, simply ensure that: static initializers of classes do not throw any unchecked exception, and that. static class variable initializations do not throw any unchecked exceptions.
By calling super(message) , we initialize the exception's error message and the base class takes care of setting up the custom message, according to the message .
There are three types of exception—the checked exception, the error and the runtime exception.
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.
You can create your own Exception by extending Exception class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With