java 如果 catch 和 finally 块都抛出异常会发生什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1482395/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 16:42:07  来源:igfitidea点击:

What happens if both catch and finally blocks throw exception?

c#java.netexceptiontry-finally

提问by Arthur

What happens if both catch and finally blocks throw exception?

如果 catch 和 finally 块都抛出异常会发生什么?

采纳答案by adrianbanks

When the finallyblock throws an exception, it will effectively hide the exception thrown from the catchblock and will be the one ultimately thrown. It is therefore important to either log exceptions when caught, or make sure that the finally block does not itself throw an exception, otherwise you can get exceptions being thrown that are stifled and never seen.

finally块抛出异常时,它会有效地隐藏从块中抛出的异常,catch并将成为最终抛出的异常。因此,重要的是在捕获时记录异常,或者确保 finally 块本身不会抛出异常,否则您可能会抛出被扼杀且从未见过的异常​​。

回答by NawaMan

When catch throws an exception, finally block will be run and then exit with an exception. If the finally block throws an exception, the block will exit with an exception.

当 catch 抛出异常时,finally 块将被运行,然后以异常退出。如果 finally 块抛出异常,则该块将退出并抛出异常。

回答by chrisb

Its already been answered well by adrianbanks, but the following post should be interesting: Interesting Exception Results: Throwing Exceptions From the Finally Block

adrianbanks 已经很好地回答了这个问题,但下面的帖子应该很有趣:有趣的异常结果:从finally 块中抛出异常

回答by Tom Hawtin - tackline

The last exception thrown is thrown.

抛出最后一个异常。

回答by sunil shetty

HI Nwaman i think you answer is wrong i have tested it in windows appliaction, i found if u write a program like the below one

嗨 Nwaman,我认为你的回答是错误的,我已经在 Windows 应用程序中对其进行了测试,我发现你是否编写了如下程序

try
{
    string s = "hu";
    int i = int.Parse(s);
}
catch (Exception ex)
{
    string s = "hu";
    int i = int.Parse(s);
    throw new Exception();
}
finally
{
    MessageBox.Show("hi");
}

and this will not result finally to excute,

这不会导致最终执行,