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

爱⌒轻易说出口 提交于 2019-12-06 16:32:00

问题


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

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



回答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 {
    // ...
}



回答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
  }
}


来源:https://stackoverflow.com/questions/10736238/in-a-finally-block-can-i-tell-if-an-exception-has-been-thrown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!