← Back to Home

Module 4: Exceptions

Module Overview

Learn about exception handling and error management in Java to create more robust and fault-tolerant applications.

Learning Objectives

Key Concepts Explained

Exception handling is a crucial part of Java programming that allows developers to manage errors and unexpected situations gracefully.

Understanding Exceptions

Exceptions are events that disrupt the normal flow of program execution. They are objects that inherit from the java.lang.Throwable class.

The Java exception hierarchy:

Throwing Exceptions

Use the throw keyword to throw an exception when invalid inputs or states are detected.

public void deposit(double amount) {
    if (amount <= 0) {
        throw new IllegalArgumentException("Deposit amount must be positive");
    }
    
    this.balance += amount;
}
            

NullPointerException

A NullPointerException is thrown automatically by the JVM when a program attempts to use a null reference where an object is required.

String name = null;

// This will throw a NullPointerException
int length = name.length(); 

// Prevent NullPointerException with a null check
if (name != null) {
    int length = name.length();
}
            

Try-Catch-Finally

Use try-catch blocks to handle exceptions and finally blocks to ensure cleanup code always executes.

public void readFile(String filename) {
    FileReader reader = null;
    try {
        reader = new FileReader(filename);
        // Process file contents
    } catch (FileNotFoundException e) {
        System.err.println("File not found: " + filename);
    } catch (IOException e) {
        System.err.println("Error reading file: " + e.getMessage());
    } finally {
        // This block always executes
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                System.err.println("Error closing file");
            }
        }
    }
}
            

Custom Exceptions

Create custom exception classes to provide more specific information about errors in your application.

// Custom exception class
public class InsufficientFundsException extends Exception {
    private double amount;
    
    public InsufficientFundsException(double amount) {
        super("Insufficient funds: Needed $" + amount + " more");
        this.amount = amount;
    }
    
    public double getAmount() {
        return amount;
    }
}

// Using the custom exception
public void withdraw(double amount) throws InsufficientFundsException {
    if (amount > balance) {
        throw new InsufficientFundsException(amount - balance);
    }
    
    balance -= amount;
}
            

Key Topics

Exception Basics

  • Checked vs. unchecked exceptions
  • Exception hierarchy
  • Common exceptions in Java
  • Stack traces and debugging

Exception Handling

  • Try-catch blocks
  • Try-with-resources
  • Finally blocks
  • Multi-catch statements

Custom Exceptions

  • Creating custom exception classes
  • Exception design principles
  • When to create custom exceptions
  • Exception documentation

Guided Practice

Additional Resources

Next Steps

After completing this module:

  1. Practice implementing exception handling in your code
  2. Create a custom exception for a specific use case
  3. Review the code-along materials for additional practice
  4. Prepare for the Sprint Challenge by reviewing all modules