Java MCQ

Previous Java Multiple Choice Questions Next

JAVA TRICKY exception handling MCQ

1

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"); }

Correct Answer: A) ABC

A is printed, exception is thrown and caught (B), finally block always executes (C).

2

What is the output of: try { System.out.print("A"); return; } finally { System.out.print("B"); }

Correct Answer: C) AB

Finally block executes even when return statement is encountered in try block.

3

What is the output of: try { throw new IOException(); } catch (IOException e) { throw new RuntimeException(); } finally { System.out.print("Finally"); }

Correct Answer: C) Finally followed by Runtime exception

Finally block executes before the RuntimeException is propagated up the call stack.

4

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"); }

Correct Answer: A) A

ArrayIndexOutOfBoundsException is caught by the first catch block since it's more specific than Exception.

5

What is the output of: class Test { void show() throws IOException { } } class Child extends Test { void show() throws Exception { } }

Correct Answer: B) Compilation error

Overridden method cannot throw broader checked exception. Exception is broader than IOException.

6

What is the output of: try { System.out.print("A"); System.exit(0); } finally { System.out.print("B"); }

Correct Answer: A) A

System.exit(0) terminates the JVM immediately, so finally block doesn't execute.

7

What is the output of: try { int x = 10/0; } catch (ArithmeticException e) { System.out.print("A"); } catch (RuntimeException e) { System.out.print("B"); }

Correct Answer: A) A

ArithmeticException is caught by the first catch block as it's more specific than RuntimeException.

8

What is the output of: try { throw new Error(); } catch (Exception e) { System.out.print("A"); } finally { System.out.print("B"); }

Correct Answer: D) B followed by Error

Error is not caught by Exception catch block. Finally executes, then Error propagates.

9

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"); }

Correct Answer: C) Compilation error

FileNotFoundException is a subclass of IOException, so it must come before IOException in catch blocks.

10

What is the output of: try { throw new NullPointerException(); } catch (NullPointerException e) { throw e; } finally { System.out.print("Finally"); }

Correct Answer: C) Finally followed by NullPointerException

Finally block executes before the re-thrown exception propagates up the call stack.

Previous Java Multiple Choice Questions Next