第二次捕获断裂汇编(第一个不及
我有此代码:
try {
// if (false) { //(need to add this, otherwise it doesn't compile)
// throw new CountDownExc(-1);
// }
return ad2;
} catch (StackOverflowExc | NoClassDefFoundError e) {
throw new CountDownExc(50);
} catch (CountDownExc e) {
if (!e.surfaced()) {
e.dec();
throw e;
}
return 0.0;
}
如果我不添加注释的代码,则不会与:
错误:异常CountdownExc永远不会抛出相应的主体 尝试语句
为什么?
最重要的是,为什么第一个捕获不会导致编译器抱怨(但第二个障碍似乎是错误的)
I have this code:
try {
// if (false) { //(need to add this, otherwise it doesn't compile)
// throw new CountDownExc(-1);
// }
return ad2;
} catch (StackOverflowExc | NoClassDefFoundError e) {
throw new CountDownExc(50);
} catch (CountDownExc e) {
if (!e.surfaced()) {
e.dec();
throw e;
}
return 0.0;
}
And if I don't add the commented code it doesn't compile with a:
error: exception CountDownExc is never thrown in body of corresponding
try statement
Why?
Most of all, why does the first catch doesn't cause the compiler to complain (but the second block seems to be wrong)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码存在两个问题:
本质上,您需要将检查的异常视为逻辑的一部分,您只能将其重新启动或通过
catch> catch
来处理它们。如果您需要避免catch(CountDownExc)
是将抛出CountDownExc
声明声明到您的方法中,则唯一的其他选项是。看起来您打算在第一个
catch
块中捕获两种异常类型,在第一个捕获块中投掷CountdownExc
,然后在第二个catch
块。这不会飞,因为catch
阻止try
块中抛出的东西,而不是catch
block中。由于CountDownExc
是一个检查的例外,这将导致另一个汇编错误,除非您要么将try
- catch 在另一个中包装
catch 尝试 -catch
(不良练习)或添加投掷
声明。由于您的
catch
throwCountdownExc
的异常必须在其他地方处理,因此可能已经考虑到 - 我无法分辨,因为您的其余代码未知。然而,您的直接问题来自以下事实,您的
尝试
块中没有任何东西可以抛出CountDownExc
和CountDownExc
是一个检查的例外,请参见第一关联。There is a couple of problems with your code:
Essentially you need to consider checked exceptions as part of your logic and you can only either rethrow them or handle them via
catch
. The only other option if you need to avoidcatch( CountDownExc )
is to add athrows CountDownExc
declaration to your method.It looks like you intend on catching two exception types in the first
catch
block, throwCountDownExc
in that first catch block, then handle it in the secondcatch
block. That's not gonna fly, becausecatch
blocks handle what is thrown in atry
block, not in acatch
block. SinceCountDownExc
is a checked exception this is going to result in another compilation error, unless you either wrap yourtry
-catch
in anothertry
-catch
(bad practice) or add athrows
declaration.Since both of your
catch
es throwCountDownExc
the exception will have to be handled elsewhere anyway, so this may already be accounted for - I cannot tell, because the rest of your code is unknown.Your immediate problem however comes from the fact, that nothing in your
try
block is able to throwCountDownExc
andCountDownExc
is a checked exception, see first link.