Can constructors throw exceptions in Java? -


are constructors allowed throw exceptions?

yes, constructors can throw exceptions. means new object eligible garbage collection (although may not collected time, of course). it's possible "half-constructed" object stick around though, if it's made visible earlier in constructor (e.g. assigning static field, or adding collection).

one thing careful of throwing exceptions in constructor: because caller (usually) have no way of using new object, constructor ought careful avoid acquiring unmanaged resources (file handles etc) , throwing exception without releasing them. example, if constructor tries open fileinputstream , fileoutputstream, , first succeeds second fails, should try close first stream. becomes harder if it's subclass constructor throws exception, of course... becomes bit tricky. it's not problem often, it's worth considering.


Comments