Java MCQ
JAVA TRICKY exception handling MCQ
What is the output of: try { System.out.print("A"); throw new RuntimeException(); } catch (Exception e) { System.out.print("B"); } finally { System.out.print("C"); }
A is printed, exception is thrown and caught (B), finally block always executes (C).
What is the output of: try { System.out.print("A"); return; } finally { System.out.print("B"); }
Finally block executes even when return statement is encountered in try block.
What is the output of: try { throw new IOException(); } catch (IOException e) { throw new RuntimeException(); } finally { System.out.print("Finally"); }
Finally block executes before the RuntimeException is propagated up the call stack.
What is the output of: try { int[] arr = new int[5]; System.out.println(arr[10]); } catch (ArrayIndexOutOfBoundsException e) { System.out.print("A"); } catch (Exception e) { System.out.print("B"); }
ArrayIndexOutOfBoundsException is caught by the first catch block since it's more specific than Exception.
What is the output of: class Test { void show() throws IOException { } } class Child extends Test { void show() throws Exception { } }
Overridden method cannot throw broader checked exception. Exception is broader than IOException.
What is the output of: try { System.out.print("A"); System.exit(0); } finally { System.out.print("B"); }
System.exit(0) terminates the JVM immediately, so finally block doesn't execute.
What is the output of: try { int x = 10/0; } catch (ArithmeticException e) { System.out.print("A"); } catch (RuntimeException e) { System.out.print("B"); }
ArithmeticException is caught by the first catch block as it's more specific than RuntimeException.
What is the output of: try { throw new Error(); } catch (Exception e) { System.out.print("A"); } finally { System.out.print("B"); }
Error is not caught by Exception catch block. Finally executes, then Error propagates.
What is the output of: try { FileInputStream file = new FileInputStream("nonexistent.txt"); } catch (FileNotFoundException e) { System.out.print("A"); } catch (IOException e) { System.out.print("B"); }
FileNotFoundException is a subclass of IOException, so it must come before IOException in catch blocks.
What is the output of: try { throw new NullPointerException(); } catch (NullPointerException e) { throw e; } finally { System.out.print("Finally"); }
Finally block executes before the re-thrown exception propagates up the call stack.