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

Solution 1:

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

Solution 2:

Two solutions: call reportEndWorkflow twice, once in a catch block and once in the end of try:

try {
    // ...
    reportEndWorkflow("success");
} catch (MyException ex) {
    reportEndWorkflow("failure");
}

Or you can introduce a boolean variable:

boolean finished = false;
try {
    // ...
    finished = true;
} finally {
    // ...
}

Solution 3:

You're there because your try-block has completed execution. Whether an exception was thrown or not.

To distinguish between when an exception occur or whether your method flow execution completed successfully, you could try doing something like this:

boolean isComplete = false;
try
{
  try
  {
    reportStartWorkflow();
    doThis();
    doThat();
    workHarder();
    isComplete = true;
  }
  catch (Exception e)
  {}
}
finally
{
  if (isComplete)
  {
    // TODO: Some routine
  }
}