Custom Exceptions & try-with-resources
Why custom exceptions?
They make errors meaningful. InsufficientBalanceException says much more than a generic Exception.
Creating one
// Checked: callers must handle it
public class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
// Unchecked: for programming mistakes
public class InvalidLevelException extends RuntimeException {
public InvalidLevelException(String message) { super(message); }
}
- Extend
Exception→ checked. - Extend
RuntimeException→ unchecked.
try-with-resources (Java 7+)
Files, database connections and network streams must be closed. Declare them in the try (...) and Java closes them automatically, even if an error happens:
try (BufferedReader reader = Files.newBufferedReader(Path.of("notes.txt"))) {
System.out.println(reader.readLine());
} catch (IOException e) {
System.out.println("Couldn't read file: " + e.getMessage());
}
It works with any class that implements AutoCloseable. You can list several resources separated by ;.
Best practices ✅
- Never swallow exceptions with an empty
catch {}. At least log them. - Catch the most specific type you can handle.
- Write clear messages that include the bad value:
"Level must be 1–10, got 42". - Don't use exceptions for normal control flow. Check with
iffirst when you can. - Keep the original cause when wrapping:
throw new AppException("Save failed", e);
Example
class InsufficientBalanceException extends Exception {
InsufficientBalanceException(String msg) { super(msg); }
}
class Wallet {
private int coins = 100;
void spend(int amount) throws InsufficientBalanceException {
if (amount > coins) {
throw new InsufficientBalanceException(
"Need " + amount + " coins but only have " + coins);
}
coins -= amount;
}
}
public class Shop {
public static void main(String[] args) {
Wallet w = new Wallet();
try {
w.spend(30);
w.spend(500);
} catch (InsufficientBalanceException e) {
System.out.println("🛑 " + e.getMessage());
}
}
}
// 🛑 Need 500 coins but only have 70