Lesson 7 of 13
Exception Handling
Learn how to catch and throw in Java, including checked exceptions, which the requires you to either handle or declare.
import java.io.*;
import java.util.*;
public class ExceptionHandling {
// Checked exception — must declare or catch it
public static String readFile(String path) throws IOException {
StringBuilder sb = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
}
return sb.toString(); // auto-closes reader (try-with-resources)
}
// Custom exception
static class InsufficientFundsException extends RuntimeException {
private final double amount;
private final double balance;
InsufficientFundsException(double amount, double balance) {
super(String.format("Cannot withdraw %.2f, balance is %.2f", amount, balance));
this.amount = amount;
this.balance = balance;
}
public double getAmount() { return amount; }
public double getBalance() { return balance; }
}
public static void main(String[] args) {
// try-catch-finally
try {
String content = readFile("data.txt");
System.out.println(content);
} catch (FileNotFoundException e) {
System.err.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.err.println("IO error: " + e.getMessage());
} finally {
System.out.println("Always runs");
}
// Multi-catch (Java 7+)
try {
int[] arr = {1, 2, 3};
int n = Integer.parseInt("abc");
System.out.println(arr[n]);
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
System.err.println("Error: " + e.getMessage());
}
}
}Finished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.