Java
Beginner
1 min read
Checked vs Unchecked Exceptions
Example
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
// Custom checked exception
class InsufficientFundsException extends Exception {
private final double amount;
InsufficientFundsException(double amount) {
super("Insufficient funds: need " + amount + " more");
this.amount = amount;
}
public double getAmount() { return amount; }
}
// Custom unchecked exception
class InvalidAccountException extends RuntimeException {
InvalidAccountException(String id) {
super("Account not found: " + id);
}
}
public class ExceptionTypesDemo {
static void withdraw(double balance, double amount)
throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(amount - balance);
}
System.out.println("Withdrew: " + amount);
}
static void openAccount(String id) {
if (id == null || id.isBlank()) {
throw new InvalidAccountException(id); // unchecked
}
}
public static void main(String[] args) {
// Checked exception — must handle
try {
withdraw(100.0, 150.0);
} catch (InsufficientFundsException e) {
System.out.println("Caught: " + e.getMessage());
System.out.println("Short by: " + e.getAmount());
}
// Unchecked exception
try {
openAccount("");
} catch (InvalidAccountException e) {
System.out.println("Caught unchecked: " + e.getMessage());
}
}
}