Complete the code to catch an exception when dividing by zero.
try { int result = 10 / [1]; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero."); }
Dividing by zero causes an ArithmeticException, so the blank must be 0 to trigger the exception.
Complete the code to handle a possible null pointer exception.
String text = null; try { int length = text.[1](); } catch (NullPointerException e) { System.out.println("Text is null."); }
The method length() is called on a null string, which causes NullPointerException.
Fix the error in the code to properly catch exceptions.
try { int[] arr = new int[3]; int value = arr[5]; } catch ([1] e) { System.out.println("Index out of bounds."); }
Accessing an invalid array index throws ArrayIndexOutOfBoundsException.
Fill both blanks to create a try-catch block that handles file reading exceptions.
try { FileReader file = new FileReader("test.txt"); BufferedReader reader = new BufferedReader(file); String line = reader.readLine(); } catch ([1] e) { System.out.println("File not found."); } catch ([2] e) { System.out.println("IO error occurred."); }
FileNotFoundException handles missing file errors, IOException handles other input/output errors.
Fill all three blanks to create a method that throws and catches a custom exception.
class MyException extends Exception {} public class Test { public static void check(int num) throws [1] { if (num < 0) { throw new [2](); } } public static void main(String[] args) { try { check(-1); } catch ([3] e) { System.out.println("Custom exception caught."); } } }
The method declares throwing MyException, throws it when condition meets, and catches it in main.