Complete the code to ensure the block always runs after try.
try { System.out.println("Try block"); } [1] { System.out.println("This always runs"); }
The finally block always runs after the try block, regardless of exceptions.
Complete the code to catch an exception and still run the final block.
try { int a = 5 / 0; } [1] (ArithmeticException e) { System.out.println("Caught division by zero"); } finally { System.out.println("Always runs"); }
The catch block handles exceptions. It must be followed by parentheses with the exception type.
Fix the error in the finally block declaration.
try { System.out.println("Try block"); } catch(Exception e) { System.out.println("Exception caught"); } [1] { System.out.println("This always runs"); }
The correct keyword for the block that always runs is finally.
Fill both blanks to complete the try-catch-finally structure.
try { int[] arr = new int[2]; System.out.println(arr[[1]]); } [2] (ArrayIndexOutOfBoundsException e) { System.out.println("Index error caught"); } finally { System.out.println("Cleanup done"); }
The index 3 is out of bounds for an array of size 2, causing an exception caught by the catch block.
Fill all three blanks to create a try-catch-finally that handles null pointer exception.
String s = null; try { System.out.println(s.[1]()); } [2] (NullPointerException e) { System.out.println("Null pointer caught"); } [3] { System.out.println("Always runs"); }
Calling length() on a null string causes a NullPointerException, caught by catch, and the finally block always runs.