Neural Sync Active
Exception Handling
Registry Synced
Exception Handling
1112 words
6 min read
Reading compass
Now · 🎯 Learning Objectives
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
pseudoThrowable ├── 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
javatry { // 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+):
javatry { // 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
javapublic void setAge(int age) { if (age < 0 || age > 150) { throw new IllegalArgumentException("Invalid age: " + age); } this.age = age; }
4.2 throws — Declaring an Exception
javapublic 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:
- Catch it (try-catch), OR
- 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
- Catch specific exceptions, not
ExceptionorThrowable - Don't swallow exceptions (empty catch block is a code smell)
- Use try-with-resources for all closeable resources
- Throw early, catch late — let the appropriate layer handle it
- Preserve the cause — chain exceptions with
causeparameter - Don't use exceptions for normal control flow
8. Common Pitfalls
Pitfall 1: Empty Catch Block
javatry { 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
javatry { /* 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
javatry { /* ... */ } 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?javatry { 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 DQ2: Difference between throw and throws?Answer:throwactually throws an exception.throwsdeclares that a method may throw an exception (caller must handle). Q3: Can you have return in try and finally? Which wins?Answer:finallywins. 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 thecauseconstructor parameter:javatry { /* read file */ } catch (IOException e) { throw new MyAppException("Read failed", e); }The original exception is preserved ingetCause(). Q7: What does try-with-resources require?Answer: Resources must implementAutoCloseable(whichCloseableextends). 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:javatry { risky(); } finally { cleanup(); }
📐 Key Concepts
| Concept | Syntax | Purpose |
|---|---|---|
| try | try { } | Wrap risky code |
| catch | catch (Type e) { } | Handle specific exception |
| finally | finally { } | Always execute cleanup |
| throw | throw new X() | Throw an exception |
| throws | throws X, Y | Declare exceptions |
| try-with-resources | try (Resource r = ...) { } | Auto-close resources |
🔗 Cross-References
- Next: I/O Streams & Serialization Join Discord Previous6.2 Collections FrameworkNext7.2 I/O Streams & Serialization