Can Constructors Throw Exceptions in Java

Can constructors throw exceptions in Java?

Yes, constructors can throw exceptions. Usually this means that the new object is immediately eligible for garbage collection (although it may not be collected for some time, of course). It's possible for the "half-constructed" object to stick around though, if it's made itself visible earlier in the constructor (e.g. by assigning a static field, or adding itself to a collection).

One thing to be careful of about throwing exceptions in the constructor: because the caller (usually) will have no way of using the new object, the constructor ought to be careful to avoid acquiring unmanaged resources (file handles etc) and then throwing an exception without releasing them. For example, if the constructor tries to open a FileInputStream and a FileOutputStream, and the first succeeds but the second fails, you should try to close the first stream. This becomes harder if it's a subclass constructor which throws the exception, of course... it all becomes a bit tricky. It's not a problem very often, but it's worth considering.

Subclassing from classses with Java Constructors throwing Exceptions

Why does it work the opposite in constructors, the constructor of
subclass has to throw the same exception or wider, Any reasonable
explanation for this?

A subclass constructor always invokes its parent constructor with a call to super(..). In this case, the parent constructor is declared as throwing a checked exception of type MyException. Your subclass constructor must be able to handle that (with a throws since super(..) has to be the first statement in the constructor body).

With methods, you're not forced to invoke the super implementation.

Throw exception for default constructor java

I ended up adding this:

 public DictionaryException(String error_string)
{
System.out.println(error_string);
}

as the default constructor for DictionaryException

And then:

public HashDictionary() throws DictionaryException {
throw new DictionaryException("Default constructor should not be used!");
}

This for the default constructor of the HashDictionary, the issue was that the type was a boolean, so I removed that and it seemed to work.

When to throw exceptions for constructor

Well... It is a matter of taste.

If the preconconditions for the class is that rootRegion has to be provided, it makes sense to protect the class implementation from the need to make null checks all over the place.

So to answer the question "When should I throw exception in a constructor" : I would do it in all cases where the parameters, from the consumer, brings your implementation in a invalid state, delegate the problem (ie. throw the exception).

If you try to take the role as consumer for a while, and you choose not to make the null-checks he will have code like:

Neocortex n = new Neocortex(null,null);
n.doSomeething();

If he reach the 2nd line, and the implementation here throws a NullPointerException it will not be clear for him that it is due to the parameters he provided.

Throwing exceptions from constructor - is it necessary subclass has to throw as well?

Well each subclass will chain to a superclass constructor. In your case, that's happening implicitly - for example this:

public TestConstructorException(int x) {
}

is equivalent to

public TestConstructorException(int x) {
super();
}

You can't catch any exception thrown by that superclass constructor within the subclass constructor as the chaining to the superclass constructor must be the very first thing in the constructor body - you can't even start a try block.

So, what would you expect your subclass constructor to do if the superclass constructor threw an exception?

Is it okay for constructors to throw runtime exceptions?

Yes, this is inevitable in many constructors anyway when they call other methods since there is always a possibility that they will already throw unchecked exceptions.

When is it right for a constructor to throw an exception?

The constructor's job is to bring the object into a usable state. There are basically two schools of thought on this.

One group favors two-stage construction. The constructor merely brings the object into a sleeper state in which it refuses to do any work. There's an additional function that does the actual initialization.

I've never understood the reasoning behind this approach. I'm firmly in the group that supports one-stage construction, where the object is fully initialized and usable after construction.

One-stage constructors should throw if they fail to fully initialize the object. If the object cannot be initialized, it must not be allowed to exist, so the constructor must throw.

Is it okay to throw exceptions from the constructor in this case?

I don't see anything wrong from throw an exception in the constructor. It means that the object can't be created in a valid state.

Personally you throw the right exception, but don't use custom exceptions if you can use Java exceptions InvalidLevelException and InvalidYearException should be replaced with IllegalArgumentException while NullPointerException is the right exception if an argument is null.

Another thing i would change is the style: Check your arguments then do everything else.

public Course(String name, String code, char level, int academicYear)
{
if (name == null) {
throw new NullPointerException("Name can not be null.");
}
if (code == null) {
throw new NullPointerException("Code can not be null.");
}

if (indexOf(level, VALID_LEVEL) == -1) {
throw new InvalidLevelException("Level must be one of "
+ "characters defined in the public array in Course.");
}

if (String.valueOf(academicYear).length() != NUMBER_OF_DIGITS_IN_YEAR) {
throw new InvalidYearException("Year must be a four digit number!");
}

serialNumber = nextSerialNumber++;
this.code = code;
this.academicYear = academicYear;
this.level = level;
this.name = name;
}

(p.s if the object can't be created, why increment serial number?)

It's very elegant right? -- Another thing is to make the messages more specific.

Anyway, i think the best source is the entire JDK platform since it's a common pattern to thrown an exception in the constructor.


As Luiggi Mendoza said in comments, it's HashMap constructor if you need a prof for your teacher

187     public More ...HashMap(int initialCapacity, float loadFactor) {
188 if (initialCapacity < 0)
189 throw new IllegalArgumentException("Illegal initial capacity: " +
190 initialCapacity);
191 if (initialCapacity > MAXIMUM_CAPACITY)
192 initialCapacity = MAXIMUM_CAPACITY;
193 if (loadFactor <= 0 || Float.isNaN(loadFactor))
194 throw new IllegalArgumentException("Illegal load factor: " +
195 loadFactor);
196
197 // Find a power of 2 >= initialCapacity
198 int capacity = 1;
199 while (capacity < initialCapacity)
200 capacity <<= 1;
201
202 this.loadFactor = loadFactor;
203 threshold = (int)(capacity * loadFactor);
204 table = new Entry[capacity];
205 init();
206 }


Related Topics



Leave a reply



Submit