This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Exception Handling Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Exception Handling" Watch "Exception Handling" New topic

Exception Handling

Swaranga Sarma

Joined: Dec 17, 2010
Posts: 12
I need help on this. We know that a finally block will be executed even if no Exceptions are thrown. But how do we check if we are in the finally block after an exception has been thrown or following normal course of program execution. We can use manual methods like setting a boolean flag to true in the catch block and then checking the value of the boolean flag in the finally block; but I am more interested if there are any automatic methods or APIs.
Christophe Verré

Joined: Nov 24, 2005
Posts: 14688

but I am more interested if there are any automatic methods or APIs.

None. finally should be independent of normal flow and exceptions.

[My Blog]
All roads lead to JavaRanch
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15094

Welcome to JavaRanch.

Why would you want to check in the finally block if an exception happened before you got there? You should handle the exception in the catch block, so that you don't have to do anything special for it in the finally block. Can you give a code example that shows why you would want to do this?

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Nuwan Arambage
Ranch Hand

Joined: May 05, 2010
Posts: 76
yes again, it is important to understand why finally block is added to the Java exception handling mechanism.The intent is to execute the code that you need to run irrespective of the normal clause or exceptional clause.

For a example, most of the resource clean up is being done under the final block.I don't know if there is a method for handling you requirement.

Nuwan Arambage
Swaranga Sarma

Joined: Dec 17, 2010
Posts: 12
Since I am not allowed to share the exact code due to legal issues this is more or less what I am trying to do :

I need to do it this way because the "cleanup" code in the finally block may throw additional exceptions. We have to throw them back to the caller function but if there was an exception thrown in the try block those exceptions must take precedence and be thrown instead.
I agree. Here's the link:
subject: Exception Handling
It's not a secret anymore!