java 在 finally 块中,我可以判断是否抛出了异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10736238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In a finally block, can I tell if an exception has been thrown
提问by Kevin
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 ?
我有一个工作流方法可以做事情,如果发生错误就会抛出异常。我想将报告指标添加到我的工作流程中。在下面的 finally 块中,有没有办法判断 try/catch 块中的方法之一是否引发了异常?
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();
}
}
回答by Marko Topolnik
There is no automatic way provided by Java. You could use a boolean flag:
Java 没有提供自动方式。您可以使用布尔标志:
boolean success = false;
try {
reportStartWorkflow();
doThis();
doThat();
workHarder();
success = true;
} finally {
if (!success) System.out.println("No success");
}
回答by Vivien Barousse
Two solutions: call reportEndWorkflow
twice, once in a catch
block and once in the end of try
:
两种解决方案:调用reportEndWorkflow
两次,一次在catch
块中,一次在try
:
try {
// ...
reportEndWorkflow("success");
} catch (MyException ex) {
reportEndWorkflow("failure");
}
Or you can introduce a boolean variable:
或者你可以引入一个布尔变量:
boolean finished = false;
try {
// ...
finished = true;
} finally {
// ...
}
回答by Bitmap
You're there because your try-block has completed execution. Whether an exception was thrown or not.
您在那里是因为您的 try 块已完成执行。是否抛出异常。
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
}
}