Multiple choice technology programming languages

Is this code legal ? class ExceptionA extends Exception {} class ExceptionB extends ExceptionA {} public class Test{ void thrower() throws ExceptionB{ throw new ExceptionB(); } public static void main(String[] args){ Test t = new Test(); try{t.thrower();} catch(ExceptionA e) {} catch(ExceptionB e) {} } }

  1. yes

  2. no

  3. DO NOT SELECT 1

  4. DO NOT SELECT 2

Reveal answer Fill a bubble to check yourself
B Correct answer
Explanation

The code is NOT legal. In Java, catch blocks must be ordered from most specific to most general. Since ExceptionB extends ExceptionA, catching ExceptionA first would also catch any ExceptionB instances, making the second catch block unreachable (a compile-time error). To fix this, reverse the order: catch ExceptionB first, then ExceptionA.

AI explanation

Java requires catch blocks for an exception hierarchy to be ordered from most specific to most general. Here catch(ExceptionA e) appears before catch(ExceptionB e), but ExceptionB extends ExceptionA, so the first catch block would already handle any ExceptionB thrown, making the second catch block unreachable code. The compiler detects this and rejects the program, so the code is not legal.