• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructors:True or false

 
Karen Leoh
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi..
I just want to confirm whether the following statement is true or false
Constructors can throw exceptions. If parent default constructor throw exception, subclass have to do the same or have to handle the exeption.
Thanks.
 
zarina mohammad
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Constructors can throw exceptions. If parent default constructor throw exception, subclass have to do the same or have to handle the execption

the above statement is true. the subclass whose parent constructor throws exception ,has to handle the same exception or superclass of the exception thrown by the constructor of the super class.
try the following code
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is because a subclass constructor will call the superclass constructor as its first job before executing anything else.

The superclass constructor may throw an exception which in turn may be thrown in the subclass constructor since the latter called the former.
As far as exceptions are concerned, you can see the invocation to super() as a normal method invocation which may not terminate by returning gracefully but by throwing an exception instead. The thrown exception is to be handled by the subclass constructor (try-catch) or thrown ahead...
 
Amir Ghahrai
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
just to add, that it need not declare exceptions if they are unchecked exceptions.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic