Question
Why doesn't method m2() compile when using multi-catch Exception handling in Java?
public int m2(boolean b) {
try {
throw b ? new Excep1() : new Excep2();
} catch (Excep1 | Excep2 e) {
return 0;
}
}
Answer
The m2() method does not compile due to the way Java handles type resolution in the throw statement combined with multi-catch blocks. Let’s break down why this occurs and how to resolve it.
public int m2(boolean b) {
try {
if (b) {
throw new Excep1();
} else {
throw new Excep2();
}
} catch (Excep1 | Excep2 e) {
return 0;
}
}
Causes
- Java requires that the type being thrown is known at compile time.
- The ternary operator in m2() introduces ambiguity because it evaluates to either Excep1 or Excep2, but not a common supertype that can be caught in a single catch block.
Solutions
- Refactor the m2() method to separate the catch blocks for the different exception types.
- Modify the throw statement to eliminate the ternary operator and explicitly throw each exception in an if-else structure.
Common Mistakes
Mistake: Using a ternary operator to throw different exception types.
Solution: Use an if-else statement to ensure that the compiler can clearly determine the exception type.
Mistake: Assuming all exception types can be caught in a single catch block without a common superclass in some syntaxes.
Solution: Make sure exceptions thrown in a single context can be caught by a multi-catch if they share a common superclass or refactor the statement.
Helpers
- Java multi-catch exceptions
- Java method compilation error
- Java exception handling
- Catching multiple exceptions in Java
- Java m2 method compile failure