如果抛出RuntimeException,是否可以被捕获为异常? [英] If RuntimeException is thrown, can it be caught as an Exception?
问题描述
如果我有一个尝试
块,抛出一个 RuntimException
子类,可以后续的抓取
块将其作为异常
获取?具体来说:
If I have a try
block that throws a RuntimException
subclass, can a subsequent catch
block catches it as an Exception
? Specifically:
public class MyAppException extends RuntimeException {
// ....
}
// In some other part of the code:
try {
// Executing this results with doSomething() throwing a MyAppException.
int x = doSomething();
} catch(Exception exc) {
// Does the thrown MyAppException get caught here?
}
我的想法是是,因为 RuntimeException
扩展异常
。但是我有一些生产代码没有这样做。很显然,如果答案是否定的,那就是我的答案。否则我需要挖一下,看看为什么我的代码破坏了。感谢提前!
My thinking is yes, because a RuntimeException
extends Exception
. However I have some production code that is not behaving this way. So obviously, if the answer is no, then that's my answer; otherwise I need to dig down and see why my code is breaking bad. Thanks in advance!
推荐答案
是的。它将捕获 RuntimeException
,但是如果catch块中出现任何异常
,则必须再次捕获。
Yes. It will catch RuntimeException
but in case any Exception
arise in catch block that you have to catch again.
我建议您进行本地部署并调试代码。
这篇关于如果抛出RuntimeException,是否可以被捕获为异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!