1Z0-819 · Question #9
Given: public method foo() throws FooException { ... } and omitting the throws FooException clause results in a compilation error.Which statement is true about FooException?
The correct answer is D. The body of foo can throw FooException or one o its subclasses. Option D is correct because the throws FooException clause in a method signature declares that the method may propagate FooException or any of its subclasses - a subclass instance satisfies the declared type. The critical clue is that omitting the clause causes a compilation…
Question
Options
- AFooException is a subclass of RuntimeError.
- BFooException is unchecked.
- CThe body of foo does not throw FooException.
- DThe body of foo can throw FooException or one o its subclasses.
How the community answered
(19 responses)- A5% (1)
- B16% (3)
- C5% (1)
- D74% (14)
Explanation
Option D is correct because the throws FooException clause in a method signature declares that the method may propagate FooException or any of its subclasses - a subclass instance satisfies the declared type. The critical clue is that omitting the clause causes a compilation error, which only happens with checked exceptions; Java's compiler enforces that checked exceptions are either caught or declared, but never enforces this for unchecked ones.
- A is wrong because
RuntimeErrordoesn't exist in Java (the class isRuntimeException), and subclasses ofRuntimeExceptionare unchecked - they would not cause a compile error if omitted from thethrowsclause. - B is wrong for the same core reason: if
FooExceptionwere unchecked, the compiler would not complain about omittingthrows FooException. The compile error is the dead giveaway that it's checked. - C is wrong because the compile error tells us the body does throw
FooException(or calls something that does) - if the exception were never thrown in the body, omitting the clause would be perfectly legal even for a checked exception.
Memory tip: Think of it as "checked = you must check it in with the compiler." If dropping throws breaks the build, the exception is checked - and a checked throws declaration always covers the named type plus its subclasses.
Topics
Community Discussion
No community discussion yet for this question.