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 ?
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.
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 ?
author and iconoclast
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.
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 ]