Well plz refer to page number 101 in which he says constructors cannot specify exceptions in header ..... Why is this working then ? class base { base() throws Exception { try { System.out.println("I am in the Base : Try"); throw new Exception(); } catch(Exception e) { System.out.println("I am in the Base : Catch"); } throw new Exception();
} } public class derived extends base { derived() throws Exception {
}
public static void main(String args[]) { try { new derived(); } catch(Exception e) { } } }
Vaibhav Shridish
Corey McGlone
Ranch Hand
Joined: Dec 20, 2001
Posts: 3271
posted
0
The text does not say that you can't have exceptions. There are a few notes, such as the fact that constructors have a set name (the class name) and they cannot return a value, but nowhere does it say that a constructor can not throw an exception. It doesn't say that it can, but it also doesn't say that a constructor can take parameters, either. I'm pretty sure most people realized that they can. You can take a look at the JLS, §8.8 Constructor Declarations for details about declaring a constructor. From there, you can see that it is perfectly legal to throw an exception from a constructor. Note, however, that if an exception is thrown, the object is not created. Corey
Also, make sure you check the Errata for corrections to the text.
Vaibhav Shridish
Greenhorn
Joined: Jun 06, 2002
Posts: 28
posted
0
thanz all for replies .... corey .. i have gone thru the declarations section i was under the impression that const cannot THROW exceptions ... Then what did the statement from rasmussen mean ? "constructors cannot specify exceptions in header" ??
Corey McGlone
Ranch Hand
Joined: Dec 20, 2001
Posts: 3271
posted
0
Perhaps you have a previous printing of that text because mine does not say that. Be sure to check the errata page that Jess referenced. Constructors CAN throw exceptions. Corey
Originally posted by Corey McGlone: Constructors CAN throw exceptions.
However, "Initializer blocks cannot pass on checked exceptions, only unchecked ones." -- Mughal&Rasmussen pg 259, 8.2 Initializers
Pierre Post
Greenhorn
Joined: Jun 18, 2002
Posts: 12
posted
0
However, "Initializer blocks cannot pass on checked exceptions, only unchecked ones." -- Mughal&Rasmussen pg 259, 8.2 Initializers
... "unless that exception or one of its superclasses is explicitly declared in the throws clause of each constructor of its class and the class has at least one explicitly declared constructor. An instance initializer in an anonymous class can throw any exceptions." (JLS �8.6) I think this is important as I had one or two mock exams where this was asked.