Understanding Exception Handling

1. Understanding Exception Hierarchy

Exception hierarchy

Throwable
├── Error                   (unrecoverable: OOM, StackOverflow)
└── Exception               (checked)
    ├── IOException
    ├── SQLException
    └── RuntimeException    (unchecked)
        ├── NullPointerException
        ├── IllegalArgumentException
        ├── IndexOutOfBoundsException
        └── ClassCastException
TypeCatch?Declare?
ErrorDon'tNo
Checked ExceptionYesYes
RuntimeExceptionOptionalNo

2. Using try-catch Blocks

Example: try-catch

try {
    int n = Integer.parseInt(input);
} catch (NumberFormatException e) {
    log.error("Invalid number: {}", input, e);
    return -1;
}
ElementDetail
tryCode that may throw
catchHandle specific exception type
Multiple catchesMost specific first

3. Catching Multiple Exceptions

Example: Multi-catch

try {
    process(file);
} catch (IOException | SQLException e) {   // Java 7+
    log.error("Failure", e);
    throw new ServiceException(e);
}
Pipe (|) Multi-catchDetail
Variable eImplicitly final
TypeCommon supertype
ExclusionTypes must not be in same hierarchy

4. Using finally Block

AspectDetail
Always runsAfter try/catch (success or failure)
Skipped only whenSystem.exit() or JVM crash
Modern alternativetry-with-resources for cleanup
Warning: Avoid return in finally — it overrides try/catch returns.

5. Using try-with-resources

Example: Auto-close

try (BufferedReader r = Files.newBufferedReader(path);
     OutputStream out = Files.newOutputStream(target)) {
    r.lines().forEach(line -> write(out, line));
} catch (IOException e) {
    log.error("IO error", e);
}
AspectDetail
RequiresResource implements AutoCloseable
Close orderReverse of declaration
Effectively-finalPre-declared resource (Java 9+) allowed

6. Throwing Exceptions

FormExample
Built-inthrow new IllegalStateException("msg");
With causethrow new ServiceException("...", cause);
Rethrowthrow e;

7. Declaring Exceptions

AspectDetail
throws clauseRequired for checked exceptions
MultipleComma-separated
Override ruleSubclass cannot add new checked exceptions

8. Creating Custom Exceptions

Example: Custom exception

public class OrderNotFoundException extends RuntimeException {
    private final String orderId;
    public OrderNotFoundException(String orderId) {
        super("Order not found: " + orderId);
        this.orderId = orderId;
    }
    public String getOrderId() { return orderId; }
}
ChoiceUse
Extend RuntimeExceptionMost app-level errors
Extend ExceptionRecoverable, force caller to handle
ConstructorsProvide message + cause overloads

9. Understanding Checked vs Unchecked Exceptions

AspectCheckedUnchecked
Compile-time checkYes (must catch/declare)No
Base classException (not RuntimeException)RuntimeException
Use caseRecoverable I/O, parsingProgramming errors, invariant violations

10. Rethrowing Exceptions

Example: Wrap and rethrow

try {
    parse(data);
} catch (ParseException e) {
    throw new DataException("Failed to parse", e);  // chain cause
}
PatternUse
WrapTranslate to higher-level exception
Plain rethrowPreserve original (Java 7+ precise rethrow)

11. Understanding Suppressed Exceptions

ConceptDetail
Sourcetry-with-resources close failures
Accesse.getSuppressed() returns array
Manual adde.addSuppressed(other)

12. Using Exception Chaining

MethodUse
Constructor causenew X(msg, cause)
initCause(c)Set cause after creation
getCause()Retrieve original

13. Understanding Best Practices

PracticeDetail
Catch specificAvoid catching Exception or Throwable
Don't swallowAlways log or rethrow
Preserve causePass original as cause
Fail fastValidate inputs at boundaries
Resource cleanupUse try-with-resources
Don't use exceptions for control flowPerformance + clarity