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(); } }
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.
A finally block always executes, regardless of whether an exception is thrown.
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 {}.
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.
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"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With