Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Appropriate exception for initialization error

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.

like image 944
Adam Matan Avatar asked Mar 13 '12 13:03

Adam Matan


People also ask

What is exception initializer error in Java?

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 do you handle exception initializer error?

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.

How do you initialize an exception in Java?

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 .

What are the 3 types of exceptions?

There are three types of exception—the checked exception, the error and the runtime exception.


2 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.

like image 139
Edwin Buck Avatar answered Sep 18 '22 22:09

Edwin Buck


You can create your own Exception by extending Exception class

like image 22
Rahul Borkar Avatar answered Sep 16 '22 22:09

Rahul Borkar