File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Constructors throwing exceptions!!!!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Constructors throwing exceptions!!!!!" Watch "Constructors throwing exceptions!!!!!" New topic

Constructors throwing exceptions!!!!!

Chandra Bairi
Ranch Hand

Joined: Sep 12, 2003
Posts: 152
I have read that a constructor can never throw an exception. If at all it should handle all the exceptions inside the constructor itself. It any class extends a super class which has a constructor which throws exception it is independent of the sub class constructor. Is it that the subclass constructor can throw an exception and the superclass constructor can catch it. or should the subclass constructor catch the exception and handle it self. do the exceptions propogate from subclasses to super classes and should the constructor handle their own exceptions or can the constructors throw the exceptions. Kindly make this point clear.
consider the above code and is that legal if so how and if not how thanks for any help
public class Question72
public Question72() throws IOException
throw new IOException();
public abstact class Question73 extends Question72
public abstract void method();

Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Chandra Bairi:
I have read that a constructor can never throw an exception.

Well, that's wrong; though it's true that some people say constructors *should not* throw exceptions.
Where did you read it?

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
And constructors are not inherited. So all exception handling in the subclass has no major impact to the base class constructor. The only
thing you have to worry about is that the implicit or explicit super()
call can return an exception.
I agree. Here's the link:
subject: Constructors throwing exceptions!!!!!
jQuery in Action, 3rd edition