nerdexam
Oracle

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…

Exception Handling

Question

Given: public method foo() throws FooException { ... } and omitting the throws FooException clause results in a compilation error.Which statement is true about FooException?

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)
  • A
    5% (1)
  • B
    16% (3)
  • C
    5% (1)
  • D
    74% (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 RuntimeError doesn't exist in Java (the class is RuntimeException), and subclasses of RuntimeException are unchecked - they would not cause a compile error if omitted from the throws clause.
  • B is wrong for the same core reason: if FooException were unchecked, the compiler would not complain about omitting throws 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

#checked exceptions#throws clause#exception declaration#exception hierarchy

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice