Exception Handling
Difficulty: medium
Overview
Throwable hierarchy: Error (JVM-level, e.g., OutOfMemoryError) and Exception. Checked exceptions (IOException, SQLException) must be handled or declared. Unchecked = RuntimeException subclasses (NullPointerException, ArithmeticException). "throw" raises an exception; "throws" declares it in a method signature. "finally" always executes except on System.exit() or JVM crash. Exception chaining preserves the root cause.
Practice Linked Questions
Q1. What is the purpose of a try-catch block in Java?
Select one answer before revealing.
Q2. Which of the following is a checked exception in Java?
Select one answer before revealing.
Q3. When does the finally block NOT execute in Java?
Select one answer before revealing.
Q4. What is the difference between 'throw' and 'throws' in Java?
Select one answer before revealing.
Q5. Which of the following are checked exceptions in Java? (More than one answer may be correct)
Select one answer before revealing.
Q6. Exception chaining in Java allows you to:
Select one answer before revealing.
Q7. NullPointerException is thrown in Java when:
Select one answer before revealing.
Q8. Which exception is thrown when an integer is divided by zero in Java?
Select one answer before revealing.
Q9. A user-defined exception in Java must:
Select one answer before revealing.
Q10. What is the output of the following code? try { System.out.println("A"); int x = 1 / 0; System.out.println("B"); } catch (ArithmeticException e) { System.out.println("C"); } finally { System.out.println("D"); }
Select one answer before revealing.
Q11. What is the output of the following code? static int test() { try { return 10; } finally { return 20; } } System.out.println(test());
Select one answer before revealing.
Q12. What is the output of the following code? (Lines run in order) String s = null; System.out.println("Value: " + s); System.out.println(s.length());
Select one answer before revealing.
Q13. What is the output of the following code? try { String s = null; System.out.println(s.length()); } catch (NullPointerException | ArithmeticException e) { System.out.println("Caught: " + e.getClass().getSimpleName()); }
Select one answer before revealing.
Q14. What exception propagates to the caller in the following code? static void riskyMethod() throws Exception { try { throw new RuntimeException("original"); } finally { throw new Exception("from finally"); } }
Select one answer before revealing.
Q15. Does the following code compile? Why or why not? Runnable r = () -> { throw new IOException("test"); };
Select one answer before revealing.