Complete the code to catch an ArithmeticException.
try { int result = 10 / 0; } catch ([1] e) { System.out.println("Cannot divide by zero."); }
The code tries to divide by zero, which throws an ArithmeticException. The catch block must specify ArithmeticException to handle it.
Complete the code to catch a NullPointerException.
String text = null; try { int length = text.length(); } catch ([1] e) { System.out.println("Text is null."); }
Calling length() on a null string throws a NullPointerException. The catch block must handle this exception.
Fix the error in the catch block to handle NumberFormatException.
try { int num = Integer.parseInt("abc"); } catch ([1] e) { System.out.println("Invalid number format."); }
Parsing "abc" as an integer throws a NumberFormatException. The catch block must specify this exception to handle it.
Fill both blanks to catch ArithmeticException and NullPointerException separately.
try { int result = 10 / 0; String text = null; int length = text.length(); } catch ([1] e) { System.out.println("Arithmetic error occurred."); } catch ([2] e) { System.out.println("Null pointer error occurred."); }
The first catch block handles ArithmeticException from dividing by zero. The second catch block handles NullPointerException from calling a method on null.
Fill all three blanks to catch NumberFormatException, ArithmeticException, and NullPointerException in separate catch blocks.
try { int num = Integer.parseInt("abc"); int result = 10 / 0; String text = null; int length = text.length(); } catch ([1] e) { System.out.println("Number format error."); } catch ([2] e) { System.out.println("Arithmetic error."); } catch ([3] e) { System.out.println("Null pointer error."); }
The first catch block handles NumberFormatException from parsing "abc". The second handles ArithmeticException from dividing by zero. The third handles NullPointerException from calling a method on null.