Skip to main content

Exceptions and File I/O

Exceptions​

An exception is an object that signals an error and unwinds the call stack until it is caught.

Throwable
|- Error (JVM problems: OutOfMemoryError)
|- Exception
|- RuntimeException (unchecked: NullPointerException, IllegalArgumentException)
|- IOException, SQLException ... (checked: must be handled or declared)
try {
int n = Integer.parseInt(input);
System.out.println(100 / n);
} catch (NumberFormatException e) {
System.out.println("not a number");
} catch (ArithmeticException e) {
System.out.println("division by zero");
} finally {
System.out.println("always runs");
}

Declaring and throwing​

static void withdraw(double amount, double balance) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("need " + (amount - balance) + " more");
}
}

class InsufficientFundsException extends Exception {
InsufficientFundsException(String msg) { super(msg); }
}

try-with-resources​

Closes AutoCloseable resources automatically, even on error.

import java.nio.file.*;
import java.io.*;

try (BufferedReader br = Files.newBufferedReader(Path.of("notes.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("failed: " + e.getMessage());
}

Modern file helpers​

String text = Files.readString(Path.of("notes.txt"));
Files.writeString(Path.of("out.txt"), "hello");
List<String> lines = Files.readAllLines(Path.of("notes.txt"));

Good practices​

  • Catch the most specific exception you can handle; do not swallow exceptions silently.
  • Do not use exceptions for normal control flow.
  • Wrap low-level exceptions with context (new ServiceException("...", cause)).
  • Prefer Optional over returning null for "no value".