• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

variable initialization

 
Greenhorn
Posts: 28
  • 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?
 
Ranch Hand
Posts: 1296
  • 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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh yeah... Welcome to JavaRanch!
 
bernard adaba
Greenhorn
Posts: 28
  • 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?
 
Ranch Hand
Posts: 62
  • 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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i think it is clear now.
thank you all
 
A sonic boom would certainly ruin a giant souffle. But this tiny ad would protect it:
how do I do my own kindle-like thing - without amazon
https://coderanch.com/t/711421/engineering/kindle-amazon
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!