• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on constructors

 
Jui Mahajan
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1.Default constructors do not ( or cannot) have a throws clause. Does this apply to only implicit constructors, or explicit constructors, or both ?
2.Also, are constructors other than default constructors allowed to throw exceptions ?
3. Where can i get good material regarding exceptions and constructors ?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In general, constructors, default or not, are allowed to throw exceptions. "Implicit" ones -- ones generated by the compiler -- won't, and this can be a problem if a superclass has a default constructor that throws; under these circumstances, the compiler won't be able to generate a constructor for a subclass.
Aside from this, the most important thing to know about exceptions and constructors is that if a constructor throws, it's as if the object never existed. The "new" expression never returns; no object is created.
 
Jui Mahajan
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you. But I have a further question. What happens if such a constructor is called (one that throws exceptions)with a new operator...u said that no object is created, so what exactly happens...is a compile time error reported ?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, the code compiles, of course -- given all the normal conditions (the call must be in a try block, or in a method that declares the same exception.) I was talking about runtime. If an exception is thrown at runtime, the object doesn't get created. If no exception is thrown, then everything proceeds as normal.
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where can i get good material regarding exceptions and constructors ?
Well, some people like the JLS and other people do not...
JLS 8.8 Constructor Declarations
JLS 8.8.4 Constructor Throws
JLS 8.4.4 Method Throws
JLS 8.8.7 Default Default Constructor
See JLS 8.8 Constructor Declarations
[ July 19, 2003: Message edited by: Marlene Miller ]
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic