Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a finally block, can I tell if an exception has been thrown [duplicate]

Possible Duplicate:
Is it possible to detect if an exception occurred before I entered a finally block?

I have a workflow method that does things, and throws an exception if an error occurred. I want to add reporting metrics to my workflow. In the finally block below, is there any way to tell if one of the methods in the try/catch block threw an exception ?

I could add my own catch/throw code, but would prefer a cleaner solution as this is a pattern I'm reusing across my project.

@Override public void workflowExecutor() throws Exception {   try {       reportStartWorkflow();       doThis();       doThat();       workHarder();   } finally {       /**        * Am I here because my workflow finished normally, or because a workflow method        * threw an exception?        */       reportEndWorkflow();    } } 
like image 429
Kevin Avatar asked May 24 '12 11:05

Kevin


People also ask

What happens if exception is thrown in finally block?

The "finally" block execution stops at the point where the exception is thrown. Irrespective of whether there is an exception or not "finally" block is guaranteed to execute. Then the original exception that occurred in the try block is lost.

Does finally execute if exception thrown?

A finally block always executes, regardless of whether an exception is thrown.

Which of the following statements about a finally block is true?

The finally block is called regardless of whether or not the related catch block is executed. Option C is the correct answer. Unlike an if-then statement, which can take a single statement, a finally statement requires brackets {}.

Can we throw exception in finally block in Java?

Methods invoked from within a finally block can throw an exception. Failure to catch and handle such exceptions results in the abrupt termination of the entire try block.


1 Answers

There is no automatic way provided by Java. You could use a boolean flag:

boolean success = false; try {   reportStartWorkflow();   doThis();   doThat();   workHarder();   success = true; } finally {   if (!success) System.out.println("No success"); } 
like image 79
Marko Topolnik Avatar answered Sep 20 '22 05:09

Marko Topolnik