JvJava
IntermediateLesson 10 of 16

Exceptions & Files – Java

Catching errors, try-with-resources and reading and writing files with java.nio.

Java has checked exceptions (the compiler forces you to handle them or declare throws, e.g. IOException) and unchecked exceptions (RuntimeException and subclasses such as NullPointerException or IllegalArgumentException).

try {
    int zahl = Integer.parseInt("abc");
    System.out.println(zahl);
} catch (NumberFormatException e) {
    System.out.println("Invalid number: " + e.getMessage());
} finally {
    System.out.println("Always executed");
}

try {
    Object o = "Text";
    Integer i = (Integer) o;
} catch (ClassCastException | NullPointerException e) {   // multi-catch
    System.out.println("Type problem: " + e.getClass().getSimpleName());
}

Custom exceptions make errors meaningful. Inherit from Exception (checked) or RuntimeException (unchecked):

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

static double abheben(double saldo, double betrag) throws NichtGenugGuthabenException {
    if (betrag > saldo) throw new NichtGenugGuthabenException("Only " + saldo + " available");
    return saldo - betrag;
}

try {
    abheben(50, 100);
} catch (NichtGenugGuthabenException e) {
    System.out.println("Error: " + e.getMessage());   // Error: Only 50.0 available
}

Resources that have to be closed (files, connections) you open with try-with-resources. They are closed automatically and in reverse order. For simple file access Files is enough:

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

Path datei = Path.of("notizen.txt");
Files.writeString(datei, "Line 1\nLine 2\n");
String alles = Files.readString(datei);
List<String> zeilen = Files.readAllLines(datei);
System.out.println(zeilen.size());          // 2

try (BufferedReader br = Files.newBufferedReader(datei)) {
    String zeile;
    while ((zeile = br.readLine()) != null) {
        System.out.println(zeile);
    }
}   // br is closed automatically here
WarningNever write an empty catch (Exception e) {} – you swallow errors invisibly. Log them, handle them sensibly or rethrow them (throw new RuntimeException("context", e); always pass the cause e along).