Complete the code to catch an exception.
try { int result = 10 / 0; } catch ([1] e) { System.out.println("Error occurred"); }
The catch block must specify an exception type to catch errors. Exception is the general type for exceptions.
Complete the code to print the exception message.
try { int[] arr = new int[2]; System.out.println(arr[5]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(e.[1]()); }
The getMessage() method returns the error message of the exception.
Fix the error in the catch block declaration.
try { int a = Integer.parseInt("abc"); } catch ([1] e) { System.out.println("Invalid number format"); }
The parseInt method throws NumberFormatException when the string is not a valid number.
Fill both blanks to catch an exception and print its message.
try { String s = null; System.out.println(s.length()); } catch ([1] e) { System.out.println(e.[2]()); }
The code throws a NullPointerException when calling length() on null. The getMessage() method prints the error message.
Fill all three blanks to catch an exception, print its message, and execute code after try-catch.
try { int[] nums = {1, 2, 3}; System.out.println(nums[[1]]); } catch ([2] e) { System.out.println(e.[3]()); } System.out.println("Program continues");
Accessing index 5 in an array of size 3 causes ArrayIndexOutOfBoundsException. The getMessage() method prints the error message. The program then continues after the catch block.