JvJava

Java: Error handling – code examples

Contents

try / catch / finally

Error handling#try#catch#exceptionCompare in all languages
Use case: Guard user input or network access without the program crashing.
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("Invalid: " + e.getMessage());
        } finally {
            System.out.println("Cleaning up");
        }
    }
}

finally always runs. The message is: For input string: "abc". For resources, try-with-resources is even better.

Optional instead of null

Error handling#optional#null
Use case: Safely handle search results that may be missing (user, configuration value).
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("unknown"));
        System.out.println(findeEmail(db, "bob").orElse("unknown"));
        findeEmail(db, "ada").ifPresent(m -> System.out.println("Sending to " + m));
    }
}

Optional makes it visible that a result can be missing. Output: ADA@EXAMPLE.COM, unknown, Sending to ada@example.com.

try-with-resources

Error handling#autocloseable#try#resources
Use case: Reliably close files, database connections or sockets.
public class Main {
    static class Verbindung implements AutoCloseable {
        final String name;
        Verbindung(String name) { this.name = name; System.out.println("opening " + name); }
        void sende(String t) { System.out.println(name + " sends " + t); }
        @Override public void close() { System.out.println("closing " + name); }
    }
    public static void main(String[] args) {
        try (var a = new Verbindung("A"); var b = new Verbindung("B")) {
            a.sende("Hi");
            b.sende("Ho");
        }
    }
}

Any class with AutoCloseable can be used in try-with-resources. Closing happens in reverse order, even with exceptions: closing B last, then closing A.