在finally块中,我可以判断是否引发了异常 [英] In a finally block, can I tell if an exception has been thrown

查看:122
本文介绍了在finally块中,我可以判断是否引发了异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

我有一个工作流程方法可以执行操作,并在发生错误时引发异常。我想将报告指标添加到我的工作流程中。在下面的finally块中,是否有任何方法可以判断try / catch块中的方法之一是否引发了异常?

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


推荐答案

有不是Java提供的自动方式。您可以使用布尔标志:

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

这篇关于在finally块中,我可以判断是否引发了异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆