Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

2 simultaneous exceptions? 3

Status
Not open for further replies.

cpjust

Programmer
Sep 23, 2003
2,132
US
Hi,
I just thought of something kind of scary, so I was wondering if anyone knows the answer.
I know in C++, if you're in a destructor because an exception was thrown and then you throw another exception, the program immediately calls the std::terminate() function and ends.

I'm wondering if the same kind of thing would happen in Java if you throw an exception from a try block and then throw another exception in a finally block? You would essentially have 2 exceptions in the air at the same time...
 
Nope. You will only have the exception from the finally block.
 
So the first exception just disappears?
So in this code:

Code:
try
{
   throw new SomeException();
}
catch ( SomeException e )
{
   throw new SomeOtherException( e );
}
finally
{
   throw new YetAnotherException();
}
Only YetAnotherException will come shooting out of the function?
 
Yes, YetAnotherAcception comes shooting out ot the function.
SomeException is caught by the catch and SomeOtherException by the finally
 
Wow, that's strange... finally catches exceptions if it throws them, but not in other cases.
But at least Eclipse gave me a warning that I was about to do something stupid in my finally block when I tried it out.
 
I wouldn't say that 'finally' actually catches exceptions. Rather, all paths lead through the finally and if you throw any exceptions from within 'finally' they silently replace any other which is pending.

Tim
 
It's funny. If you wrap that in a method, you will need to add a throws clause only for the YetAnotherException ...

Cheers,
Dian
 
The Java compilers and JVM are indeed very clever :)

Tim
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top