I'm learning chapter 5 of SCJP 6 Study Guide Exam_310-065 and in section Exception Declaration and the Public Interface it says
"Each method must either handle all checked exceptions by supplying a catch clause or list each unhandled checked exception as a thrown exception."
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.
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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.