Assuming the following program is executed with assertions enabled, which is the first line to throw an exception at runtime?
1: package mypkg; 2: public class Main { 3: public int m(int choices) { 4: assert choices++==10 : 1; 5: assert true!=false : new StringBuilder("Answer2"); 6: assert(null==null) : new Object(); 7: assert ++choices==11 : "Answer4"; 8: assert 2==3 : ""; 9: return choices; 10: } //from w w w . j a v a 2 s.co m 11: public final static void main(String... students) { 12: try { 13: new Main().m(10); 14: } catch (Error e) { 15: System.out.print("Bad idea"); 16: throw e; 17: } 18: } 19: }
D.
The Main class, including all five assert statements, compiles without issue, making Option F incorrect.
The first three assert statements on lines 4, 5, and 6 evaluate to true, not triggering any exceptions, with choices updated to 11 after the first assertion is executed.
Lines 4 and 7 demonstrate the very bad practice of modifying data in an assertion statement, which can trigger side effects.
Regardless of whether an assertion error is thrown, turning on/off assertions potentially changes the value returned by m()
.
At line 7, the assertion statement 12==11 evaluates to false, triggering an AssertionError and making Option D the correct answer.
The main()
method catches and rethrows the AssertionError.
Like writing assertion statements that include side effects, catching Error is also considered a bad practice.
Note that line 8 also would trigger an AssertionError, but it is never reached due to the exception on line 7.