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
- Extend Exception class
- Add custom fields for details
- Override getMessage() if needed
Related Exception Handling exercises
- Practice Using Throws Clause in Java
- Practice Try-With-Resources in Java
- Practice Input Validation with Exceptions in Java
Practice all Exception Handling exercises · Run this idea in the Java compiler