File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

variable initialization

 
bernard adaba
Greenhorn
Posts: 28
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What happens in the case where an exception is not thrown?
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh yeah... Welcome to JavaRanch!
 
bernard adaba
Greenhorn
Posts: 28
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is the f() method not supposed to throw the new MyException at all cost?


or it is not guaranteed?
 
Abhijeet Ravankar
Ranch Hand
Posts: 62
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 28
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i think it is clear now.
thank you all
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic