aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question on constructors Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question on constructors" Watch "Question on constructors" New topic
Author

Question on constructors

Jui Mahajan
Ranch Hand

Joined: Jun 02, 2003
Posts: 62
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 ?


-----jui<br />scjp1.4
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.


[Jess in Action][AskingGoodQuestions]
Jui Mahajan
Ranch Hand

Joined: Jun 02, 2003
Posts: 62
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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

Joined: Mar 05, 2003
Posts: 1391
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 ]
 
wood burning stoves
 
subject: Question on constructors