Which of the following best explains why exception handling is required in Java?
Think about what happens when something unexpected goes wrong during a program's execution.
Exception handling lets the program catch errors and handle them gracefully, so the program doesn't crash abruptly.
What is the output of the following Java code?
public class Test { public static void main(String[] args) { try { int result = 10 / 0; System.out.println("Result: " + result); } catch (ArithmeticException e) { System.out.println("Cannot divide by zero."); } System.out.println("Program continues."); } }
Division by zero causes an exception. The catch block handles it.
The division by zero throws an ArithmeticException, which is caught and prints the message. Then the program continues.
What will be the output of this Java code that does not use exception handling?
public class Test { public static void main(String[] args) { int[] arr = new int[3]; System.out.println(arr[5]); System.out.println("End of program."); } }
Accessing an invalid array index causes an error if not handled.
Accessing index 5 in an array of size 3 causes an ArrayIndexOutOfBoundsException and the program crashes.
Choose the correct statement about exception handling in Java.
Think about what kind of errors exception handling deals with.
Exception handling is designed to catch runtime errors and allow the program to handle them gracefully.
What will be the output of this Java program with nested try-catch blocks?
public class Test { public static void main(String[] args) { try { try { int a = 5 / 0; } catch (NullPointerException e) { System.out.println("Inner catch: NullPointerException"); } System.out.println("After inner try-catch"); } catch (ArithmeticException e) { System.out.println("Outer catch: ArithmeticException"); } System.out.println("Program ends"); } }
Consider which catch block matches the exception thrown.
The inner try throws ArithmeticException, but only catches NullPointerException, so it propagates to outer catch which handles ArithmeticException.