Custom Exception Class in Java: Explanation & Practice

Create and use custom exception

Problem summary

Create an InsufficientFundsException and throw it when withdrawal exceeds balance.

Starter code

// Create InsufficientFundsException class
// Throw when withdrawAmount > balance

public class Main {
    public static void main(String[] args) {
        double balance = 100;
        double withdraw = 150; // Test case 1
        
        // Try to withdraw, handle custom exception
    }
}

Expected output and test cases

  • Insufficient balance
    Error: Insufficient funds. Need 50.0 more
  • Valid withdrawal
    Withdrawal successful. Balance: 50.0
  • Large overdraft
    Error: Insufficient funds. Need 400.0 more

Hints

  1. Extend Exception class
  2. Add custom fields for details
  3. Override getMessage() if needed

Related Exception Handling exercises

Practice all Exception Handling exercises · Run this idea in the Java compiler