1Z0-819 · Question #77
Given: public class Test { public static void doThings() throws GeneralException { try { throw new RuntimeException("Something happened"); } catch (Exception e) { throw new…
The correct answer is D. Add extends GeneralException on line 1 Add extends GeneralException on line 2. Option D is correct because SpecificException must extend GeneralException so that throwing it inside doThings() satisfies the method's throws GeneralException declaration - the compiler requires the thrown type to be the same as or a subtype of what is declared…
Question
Options
- AAdd extends SpecificException on line 1. Add extends GeneralException on line 2.
- BAdd extends SpecificException on line 1 Add extends GeneralException on line 2
- CAdd extends Exception on line 1 Add extends Exception on line 2
- DAdd extends GeneralException on line 1 Add extends GeneralException on line 2
How the community answered
(67 responses)- A7% (5)
- B3% (2)
- C16% (11)
- D73% (49)
Explanation
Option D is correct because SpecificException must extend GeneralException so that throwing it inside doThings() satisfies the method's throws GeneralException declaration - the compiler requires the thrown type to be the same as or a subtype of what is declared. GeneralException in turn must extend Exception (the intended meaning for line 1, despite the wording), making it a proper checked exception that main's catch(Exception e) block can catch and whose getMessage() returns "Something happened".
Options A and B are wrong because they create a circular inheritance dependency - GeneralException extending SpecificException while SpecificException extends GeneralException is impossible and will not compile. Option C fails because making both classes extend Exception independently means SpecificException is not a subtype of GeneralException, so the compiler rejects throw new SpecificException(...) inside a method that only declares throws GeneralException.
Memory tip: Picture exception classes as a chain running from parent to child - the declared throws type must be an ancestor of whatever is actually thrown, and both must ultimately trace back to Exception for the catch in main to work.
Community Discussion
No community discussion yet for this question.