Given:
public static void main( String[] args ) {
try {
throw new IOException();
} catch ( IOException e ) {
throw new RuntimeException();
} finally {
throw new ArithmeticException();
}
}
What is the output?
* IOException
* RuntimeException
* ArithmeticException
* Compilation fails
#java #certificationquestion #ocp
Here's the reason:
- The `try` block throws an `IOException`.
- The `catch` block catches this exception and throws a new `RuntimeException`.
- Regardless of whether an exception was thrown or not, the `finally` block is always executed. In this case, it throws an `ArithmeticException`.
- Since the `finally` block is the last to execute and it throws an exception, the `ArithmeticException` will be the one that propagates up the call stack.
Therefore, the output will be:
* ArithmeticException
The other exceptions (`IOException` and `RuntimeException`) are thrown but not propagated, as the `ArithmeticException` from the `finally` block supersedes them. Compilation does not fail because the code is syntactically correct.