JvJava

Java: Fehlerbehandlung – Code-Beispiele

Inhalt

try / catch / finally

Fehlerbehandlung#try#catch#exceptionIn allen Sprachen vergleichen
Anwendungsfall: Nutzereingaben oder Netzwerkzugriffe absichern, ohne dass das Programm abstürzt.
public class Main {
    public static void main(String[] args) {
        try {
            int zahl = Integer.parseInt("abc");
            System.out.println(zahl);
        } catch (NumberFormatException e) {
            System.out.println("Ungültig: " + e.getMessage());
        } finally {
            System.out.println("Aufräumen");
        }
    }
}

finally läuft immer. Die Meldung lautet: For input string: "abc". Für Ressourcen ist try-with-resources noch besser.

Optional statt null

Fehlerbehandlung#optional#null
Anwendungsfall: Suchergebnisse, die fehlen können (Nutzer, Konfigurationswert), sicher behandeln.
import java.util.*;

public class Main {
    static Optional<String> findeEmail(Map<String, String> db, String name) {
        return Optional.ofNullable(db.get(name));
    }
    public static void main(String[] args) {
        var db = Map.of("ada", "ada@example.com");
        System.out.println(findeEmail(db, "ada").map(String::toUpperCase).orElse("unbekannt"));
        System.out.println(findeEmail(db, "bob").orElse("unbekannt"));
        findeEmail(db, "ada").ifPresent(m -> System.out.println("Sende an " + m));
    }
}

Optional macht sichtbar, dass ein Ergebnis fehlen kann. Ausgabe: ADA@EXAMPLE.COM, unbekannt, Sende an ada@example.com.

try-with-resources

Fehlerbehandlung#autocloseable#try#ressourcen
Anwendungsfall: Dateien, Datenbankverbindungen oder Sockets zuverlässig schließen.
public class Main {
    static class Verbindung implements AutoCloseable {
        final String name;
        Verbindung(String name) { this.name = name; System.out.println("öffne " + name); }
        void sende(String t) { System.out.println(name + " sendet " + t); }
        @Override public void close() { System.out.println("schließe " + name); }
    }
    public static void main(String[] args) {
        try (var a = new Verbindung("A"); var b = new Verbindung("B")) {
            a.sende("Hi");
            b.sende("Ho");
        }
    }
}

Jede Klasse mit AutoCloseable kann in try-with-resources stehen. Geschlossen wird in umgekehrter Reihenfolge, auch bei Exceptions: zuletzt schließe B, dann schließe A.