[英]“unhandled checked exception as a thrown exception” in Java
I'm learning chapter 5 of SCJP 6 Study Guide Exam_310-065 and in section Exception Declaration and the Public Interface it says 我正在学习SCJP 6学习指南Exam_310-065的第5章以及它所说的例外声明和公共界面部分
"Each method must either handle all checked exceptions by supplying a catch clause or list each unhandled checked exception as a thrown exception." “每个方法必须通过提供catch子句来处理所有已检查的异常,或者将每个未处理的已检查异常列为抛出异常。”
How do we list each unhandled checked exception as a thrown exception and how does it look like in the code? 我们如何将每个未处理的已检查异常列为抛出异常,以及它在代码中的外观如何? Thanks. 谢谢。
It looks like this: 它看起来像这样:
public void foo() throws SomeCheckedException, AnotherCheckedException
{
// This method would declare it in *its* throws clause
methodWhichThrowsSomeCheckedException();
if (someCondition)
{
// This time we're throwing the exception directly
throw new AnotherCheckedException();
}
}
See section 8.4.6 in the JLS for more information. 有关详细信息,请参阅JLS中的第8.4.6节 。
For instance, if you have: 例如,如果你有:
public void doSomething() throws SomeException {
...
throw new SomeException();
}
And you want to invoke doSomething
, you've got to either catch
the exception, or declare the method using it as also susceptible of throwing SomeException
, therefore propagating it further in the call stack: 并且你想要调用doSomething
,你必须要么catch
异常,要么使用它来声明方法,因为它也容易抛出SomeException
,因此在调用堆栈中进一步传播它:
public void doSomethingElse() throws SomeException {
doSomething();
}
Or 要么
public void doSomethingElse() {
try {
doSomething();
}
catch (SomeException) {
// Error handling
}
}
Take into account that RuntimeException
s are not checked exceptions, so they are an exception to this rule. 考虑到RuntimeException
不是已检查的异常,因此它们是此规则的例外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.