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

Kevin picture Kevin · May 24, 2012 · Viewed 21.5k times · Source

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(); 
  }
}

Answer

Marko Topolnik picture Marko Topolnik · May 24, 2012

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");
}