| Author |
variable initialization
|
bernard adaba
Greenhorn
Joined: May 15, 2009
Posts: 28
|
|
Hi, i am working on a code, and i kept getting a compiler error stating that variable (e1) might not have been initiliased. Why is the variable not initialised? Below is the code
class MyException extends Exception{}
class TestM {
void f() throws MyException { throw new MyException();}
public static void main(String[] args) throws MyException{
MyException e1;
TestM t = new TestM();
try{
t.f();
}
catch(MyException e){
e1=e; System.out.print("catch1");
}
finally{
try{
throw e1; // this is where the error occurs
}
catch(Exception ex){
System.out.print("catch2");
}
}
System.out.print("End");
}
}
// i was thinking when the MyException is thrown in the first try block and it is being caught, the reference variable e1 gets initialised there? So why the compiler error.?
thank you?
|
SCJP 5, SCJD
|
 |
Garrett Rowe
Ranch Hand
Joined: Jan 17, 2006
Posts: 1295
|
|
|
What happens in the case where an exception is not thrown?
|
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
|
 |
Garrett Rowe
Ranch Hand
Joined: Jan 17, 2006
Posts: 1295
|
|
|
Oh yeah... Welcome to JavaRanch!
|
 |
bernard adaba
Greenhorn
Joined: May 15, 2009
Posts: 28
|
|
is the f() method not supposed to throw the new MyException at all cost?
or it is not guaranteed?
|
 |
Abhijeet Ravankar
Ranch Hand
Joined: Mar 15, 2009
Posts: 62
|
|
|
Function f() always throws an exception. But at "Runtime". The compiler has no way to figure that out at compile-time. So, for the compiler if t.f() does not throw an exception, then the catch clause is never executed. So, e1 is never initialized. However finally always is. Hence the problem.
|
 |
bernard adaba
Greenhorn
Joined: May 15, 2009
Posts: 28
|
|
i think it is clear now.
thank you all
|
 |
 |
|
|
subject: variable initialization
|
|
|