Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception Handling

 
Swaranga Sarma
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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é
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but I am more interested if there are any automatic methods or APIs.

None. finally should be independent of normal flow and exceptions.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15274
37
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Nuwan Arambage
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Swaranga Sarma
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic