Quiz 2

Exception Handling

1112 words
6 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Exception Handling ## 🎯 Learning Objectives - Understand the Java exception hierarchy - Use try-catch-finally blocks - Distinguish checked and unchecked exceptions - Create and throw custom exceptions - Use try-with-resources for automatic resource management ## 1. What Problem Does Exception Handling Solve?

Exception Handling

🎯 Learning Objectives

  • Understand the Java exception hierarchy
  • Use try-catch-finally blocks
  • Distinguish checked and unchecked exceptions
  • Create and throw custom exceptions
  • Use try-with-resources for automatic resource management

1. What Problem Does Exception Handling Solve?

Without structured error handling, every method would need to check and propagate errors manually:
java
// Without exceptions: cluttered with error checking
int result = divide(a, b);
if (result == ERROR_DIVIDE_BY_ZERO) { /* handle */ }
// With exceptions: clean separation of normal and error paths
try {
    int result = divide(a, b);
} catch (ArithmeticException e) {
    // Handle error
}

2. Exception Hierarchy

pseudo
Throwable
  ├── Error (JVM-level, should not catch)
  │     ├── OutOfMemoryError
  │     ├── StackOverflowError
  │     └── NoClassDefFoundError
  └── Exception (program-level, should handle)
        ├── RuntimeException (unchecked)
        │     ├── NullPointerException
        │     ├── ArrayIndexOutOfBoundsException
        │     ├── ArithmeticException
        │     ├── IllegalArgumentException
        │     └── ClassCastException
        └── Checked exceptions (must handle or declare)
              ├── IOException
              ├── SQLException
              ├── FileNotFoundException
              └── ClassNotFoundException
Checked vs Unchecked:
  • Checked: Compiler forces you to handle them (catch or declare throws)
  • Unchecked (RuntimeException + Error): Not forced — usually programmer mistakes

3. try-catch-finally

java
try {
    // Code that may throw an exception
    int result = 10 / 0;  // ArithmeticException
} catch (ArithmeticException e) {
    // Handle specific exception
    System.out.println("Cannot divide by zero: " + e.getMessage());
} catch (Exception e) {
    // Catch-all — should come last
    System.err.println("Unexpected error: " + e);
} finally {
    // ALWAYS executes, even if return or exception thrown
    System.out.println("Cleanup code runs");
}
Multi-catch (Java 7+):
java
try {
    // code
} catch (IOException | SQLException e) {
    // Handle both exception types the same way
    System.err.println("Data access error: " + e.getMessage());
}

4. throw vs throws

4.1 throw — Actually Throwing an Exception

java
public void setAge(int age) {
    if (age < 0 || age > 150) {
        throw new IllegalArgumentException("Invalid age: " + age);
    }
    this.age = age;
}

4.2 throws — Declaring an Exception

java
public void readFile(String path) throws FileNotFoundException, IOException {
    // If this method throws these, the caller must handle
    FileReader reader = new FileReader(path);
    // ...
}
Checked exception rule: If a method can throw a checked exception, it must either:
  1. Catch it (try-catch), OR
  2. Declare it (throws)

5. try-with-resources (Java 7+)

Auto-closes resources implementing AutoCloseable:
java
// Before Java 7 — verbose cleanup in finally
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
    String line = br.readLine();
} finally {
    if (br != null) br.close();  // Must manually close
}
// Java 7+ — auto-close
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"));
     PrintWriter pw = new PrintWriter("out.txt")) {
    String line = br.readLine();
    pw.println(line);
} // Both br and pw automatically closed, even on exception

6. Custom Exceptions

java
// Checked custom exception
public class InsufficientBalanceException extends Exception {
    public InsufficientBalanceException(String message) {
        super(message);
    }
    public InsufficientBalanceException(String message, double deficit) {
        super(String.format("%s (deficit: %.2f)", message, deficit));
    }
}
// Unchecked custom exception
public class InvalidTransactionException extends RuntimeException {
    public InvalidTransactionException(String message, Throwable cause) {
        super(message, cause);
    }
}
// Usage:
public void withdraw(double amount) throws InsufficientBalanceException {
    if (amount > balance) {
        double deficit = amount - balance;
        throw new InsufficientBalanceException("Insufficient funds", deficit);
    }
    balance -= amount;
}

7. Best Practices

  1. Catch specific exceptions, not Exception or Throwable
  2. Don't swallow exceptions (empty catch block is a code smell)
  3. Use try-with-resources for all closeable resources
  4. Throw early, catch late — let the appropriate layer handle it
  5. Preserve the cause — chain exceptions with cause parameter
  6. Don't use exceptions for normal control flow

8. Common Pitfalls

Pitfall 1: Empty Catch Block

java
try { riskyCode(); } catch (Exception e) { /* nothing */ }
Why: Exception is silently ignored. The program continues in an invalid state.

Pitfall 2: Catching Exception Instead of Specific Types

java
try { /* code */ } catch (Exception e) { ... }
// Catches NullPointerException, ArrayIndexOutOfBounds, etc.
Better: Catch only what you can handle. Let unexpected exceptions propagate.

Pitfall 3: Swallowing Exceptions in Finally

java
try { /* ... */ } finally { return value; }  // BAD!
Why: return in finally suppresses any exception thrown in try block.

Pitfall 4: Resource Leak (Not Closing Resources)

Pre-Java 7, forgetting to close resources in finally caused leaks. Always use try-with-resources.

9. Practice Questions

Q1: What is the output?
java
try { System.out.print("A "); throw new RuntimeException(); }
catch (RuntimeException e) { System.out.print("B "); }
finally { System.out.print("C "); }
System.out.print("D ");
Answer: A B C D Q2: Difference between throw and throws?
Answer: throw actually throws an exception. throws declares that a method may throw an exception (caller must handle). Q3: Can you have return in try and finally? Which wins?
Answer: finally wins. If both have return, the finally return overrides the try return. The try's return value is discarded. Q4: Is NullPointerException checked or unchecked?
Answer: Unchecked (extends RuntimeException). The compiler doesn't force you to catch or declare it. NullPointerException indicates a programmer bug. Q5: Can a catch block throw an exception?
Answer: Yes. If it throws a checked exception not caught, the method must declare it in throws clause. If it's unchecked, no declaration needed. Q6: What is exception chaining?
Answer: Wrapping one exception inside another using the cause constructor parameter:
java
try { /* read file */ }
catch (IOException e) { throw new MyAppException("Read failed", e); }
The original exception is preserved in getCause(). Q7: What does try-with-resources require?
Answer: Resources must implement AutoCloseable (which Closeable extends). They are automatically closed in reverse order of declaration, even if an exception occurs. Q8: Can you have try without catch?
Answer: Yes, but you must have either catch or finally:
java
try { risky(); } finally { cleanup(); }

📐 Key Concepts

ConceptSyntaxPurpose
trytry { }Wrap risky code
catchcatch (Type e) { }Handle specific exception
finallyfinally { }Always execute cleanup
throwthrow new X()Throw an exception
throwsthrows X, YDeclare exceptions
try-with-resourcestry (Resource r = ...) { }Auto-close resources

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.