Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructors throwing exceptions!!!!!

 
Chandra Bairi
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic