Question discussion

What will be the output of the program?

359239Medium DSSSB TGT Computer Science 0 replies 0 views
0
What will be the output of the program?
public class ExceptionTest {
    public static void main(String[] args) {
        try {
            System.out.println("Result: " + calculate(10, 0));
        } catch (ArithmeticException e) {
            System.out.println("ArithmeticException caught: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("General exception caught: " + e.getMessage());
        } finally {
            System.out.println("In finally block.");
        }
    }
    public static int calculate(int a, int b) throws Exception {
        try {
            return a / b;
        } catch (ArithmeticException e) {
            throw new Exception("Division by zero not allowed");
        } finally {
            System.out.println("Inner finally block executed.");
        }
    }
}
  • AInner finally block executed. General exception caught: / by zero In finally block.
  • BInner finally block executed. General exception caught: Division by zero not allowed In finally block.
  • CInner finally block executed. Result: 0 In finally block.
  • DInner finally block executed. ArithmeticException caught: / by zero In finally block.
Correct answer: B

Explanation

calculate(10, 0) throws ArithmeticException, which is caught and rethrown as Exception("Division by zero not allowed"). The inner finally prints first, and main's catch (Exception) prints the message, followed by the outer finally.

Discussion 0

Nobody has replied yet. Start the discussion!