• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructors and Exceptions?

 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can constructors throw Exceptions?? Why is it said that the no-arg constructor of the superclass, must not throw an exception??
 
Campbell Ritchie
Sheriff
Pie
Posts: 49367
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20546
56
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49367
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic