English 中文(简体)
最后,我能否看出是否有例外被抛出[重复]
原标题:In a finally block, can I tell if an exception has been thrown [duplicate]
This question already has answers here:
Closed 11 years ago.

Possible Duplicate:
Is it possible to detect if an exception occurred before I entered a finally block?

我有一个工作流方法可以做一些事情, 如果出错会丢弃一个例外。 我想在我的工作流中添加报告标准。 在下面最后一块, 是否有方法可以判断试捕区是否有一种方法丢弃了一个例外?

我可以添加我自己的捕获/发射代码, 但更希望更干净的解决方案,因为这是我在整个项目中重复使用的模式。

@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没有自动提供的方法。 您可以使用布林旗 :

boolean success = false;
try {
  reportStartWorkflow();
  doThis();
  doThat();
  workHarder();
  success = true;
} finally {
  if (!success) System.out.println("No success");
}
问题回答

两种解决办法:将 reportEndWorkflow 调用两次,一次在 colpatch 块,一次在try 末尾:

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

或者您可以引入布林变量 :

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

您在那里是因为您的试管区块已完成了执行 。 是否有例外被丢弃 。

要区分出现例外或方法流程执行成功与否,您可以尝试这样做:

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




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签