Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Exception handling: Throw not initialized - can someone explain this please? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Exception handling: Throw not initialized - can someone explain this please?" Watch "Exception handling: Throw not initialized - can someone explain this please?" New topic
Author

Exception handling: Throw not initialized - can someone explain this please?

Nigel Shrin
Ranch Hand

Joined: May 18, 2009
Posts: 140

Sorry, I don't see what needs initializing, its a throw command with an instance of this simple Exception:
Is it illegal to nest another try within a finally block?







Thank you


Nigel
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

Local variables are not given their default value so you must initialize them. But because in your case this might not happen (only in the catch block) you must initialize it yourself.

Change
Whiz_MyException_ReThrow e1;
To
Whiz_MyException_ReThrow e1 = null;


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

Naj Shrin wrote:
Sorry, I don't see what needs initializing, its a throw command with an instance of this simple Exception:
Is it illegal to nest another try within a finally block?



For local variables, you are required to initialize the variable before you can use it. And the compiler will check every possible path -- if there is a path from declaration to usage without it ever being set (ie. initialized), the compiler will complain.

In this case, the compiler doesn't know that the f() method will always throw the exception, hence, the path is from the try block to the finally block -- with no exception being thrown.

Henry

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Brij Garg
Ranch Hand

Joined: Apr 29, 2008
Posts: 234
from compiler point of view,
if function f() does not throw any exception then control will never reach to catch block and e1 will never be initialized. In that case in finally block e1 is used which is local to main method and not initialized. That is why compiler is complaining.

Henry has explained very well in the above post.


Nigel Shrin
Ranch Hand

Joined: May 18, 2009
Posts: 140
Thank you Wouter, Henry & Brij
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Exception handling: Throw not initialized - can someone explain this please?