Hey all,
Can construtor throws Exceptions?? Is there anylimitation of doing that?
Printable View
Hey all,
Can construtor throws Exceptions?? Is there anylimitation of doing that?
Yep they can throw any exception you want (just mention it in the throws clause if you want it to throw a checked exception (just as with any method)). Make sure that your constructor doesn't hook up the object somewhere or allocates resources before it throws the exception.
kind regards,
Jos
HI, thanks a lot for your message!!
But why this gives an error message while compling ??/
class Test extends A{
Test()throws Exception{
System.out.println("Test10 Class");
}
Test(int i){}
public static void main(String args[]) throws Exception{
Test t = new Test();
}
}
class A{
A() throws Exception{
System.out.println("A Class");
}
}
Because If you declare that something throws an exception, you need to handle it. Consider going through the exception tutorials.
Exception Tutorials
Also, if you post code here that doesn't compile, please post the actual error message you're seeing. And if posting code, please use code tags (see link below).
unreported exception java.lang.exception, must be causge or declare to be thrown Test (int i){}
This is the error message
It looks like if one constructor throws an exception, all constructor overloads need to throw the same exception.
ya, it is something like that seems to be..
But if it is a method, overload methods no need to consider about excptions ..!! isn't it
Didn't get it where it does call implicitiy to Test (int i)?????
It's the other way around: every constructor calls either another constructor from the same class with the 'this( ... )' syntax or it calls a constructor from its superclass with the 'super( ... )' syntax. When your constructor does none of the two the compiler inserts a call to the no-args constructor of the superclass: super(). So the code for that Test(int i) constructor implicitly is:
Because that constructor of the superclass can throw an exception and your constructor doesn't handle it, it should also throw that exception. Your constructor doesn't do any of them so your compiler whined about it.Code:Test(int i) {
super(); // <--- generated by the compiler
// ...
}
kind regards,
Jos
Great explanation.. :P Thank you