为什么您需要捕获"Exception"异常?但不是子类"RuntimeException"? [英] Why do you need to catch "Exception" but not the Subclass "RuntimeException"?
问题描述
下图显示已检查"和未检查"异常是 Exception
的子类.我发现您需要捕获一个 Exception
却不捕获一个直接从 Exception
继承的 RuntimeException
令人困惑.开发人员是否有理由不让我们抛出异常而不需要捕获它们?
The below picture shows that "Checked" and "Unchecked" Exceptions are subclasses of Exception
. I find it confusing that you need to catch an Exception
but you don't need to catch a RuntimeException
, which directly inherits from Exception
. Is there a reason that the devs didn't let us throw Exceptions without needing to catch them?
更具体地说:为什么您只能忽略 RuntimeExceptions
及其子级?为什么没有引入称为 CheckedException扩展Exception
的类,而您只需要捕获它,它就是它的子类?
More specifically: Why can you ignore only RuntimeExceptions
and it's children? Why wasn't there a Class introduced called CheckedException extends Exception
and you only need to catch it and it's children?
令人困惑的部分是,您可以将所有内容扔到 RuntimeException
下而不会出现问题,但是当您移至层次结构中的 Exception
时,您需要对它进行一些了解观点.这是令人困惑的,因为抽象"通常可以正常工作.您向上移动的次数越多,所有内容都会变得越简单和越多.这里不是这种情况.您上移的次数越多,您要做的越多(例如,在达到 Exception
之后放入try/catch).
The confusing part is, that you can throw everything below RuntimeException
without issue, but when you move up to Exception
in the hierarchy, you need to catch it at some point. This is confusing because "abstraction" normally works otherwise. The more you move up, the simpler and more meta everything gets. This is not the case here. The more you move up, the more you have to do (like, putting try/catch after reaching Exception
).
推荐答案
如果未选中 Exception
,则可以将已检查的异常隐式转换为未检查的异常,这意味着您可以在不捕获的情况下抛出已检查的异常他们喜欢:
If Exception
was unchecked then you could implicitly cast checked exceptions to unchecked ones, which would mean that you could throw checked exceptions without catching them like:
public void f() {
Exception e = new IOException();
throw e;
}
以及其他重写方法,如果抛出更具体的异常,则可以添加要求以捕获超类中没有的异常:
and also with overriding methods, if you throw a more specific exception, you can add the requirement to catch the exception that wasn't in the superclass:
public void f() throws Exception {
}
...
@Override
public void f() throws IOException {
}
这篇关于为什么您需要捕获"Exception"异常?但不是子类"RuntimeException"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!