GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Constructors and Exceptions? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Constructors and Exceptions?" Watch "Constructors and Exceptions?" New topic
Author

Constructors and Exceptions?

Abhi vijay
Ranch Hand

Joined: Sep 16, 2008
Posts: 509
Can constructors throw Exceptions?? Why is it said that the no-arg constructor of the superclass, must not throw an exception??
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39084
    
  23
Yes, of course they can throw exceptions. Where did you get that from about not allowing exceptions from no-arg constructors? I couldn't find it in the Java Language Specification.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

Also, any superclass constructor can throw an exception. The only limitation is, the subclass constructor can't catch that exception so it must throw it as well.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Abhi vijay
Ranch Hand

Joined: Sep 16, 2008
Posts: 509
If the subclass has a default constructor and it calls the super constructor which throws an exception, then it will lead to compiler error, right???
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39084
    
  23
You don't write a default constructor, so you can't catch it, so it would count as an unhandled exception and (if checked) would cause a compiler error.
 
GeeCON Prague 2014
 
subject: Constructors and Exceptions?