Skip to content
Java

Exception Handling

try-catch-finally und benutzerdefinierte Exceptions.

#exception#exception

Code

java
// try-catch-finally
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.err.println("Arithmetic exception: " + e.getMessage());
} finally {
    System.out.println("Always executes");
}

// try-with-resources
try (var reader = new java.io.FileReader("file.txt")) {
    int ch;
    while ((ch = reader.read()) != -1) {
        System.out.print((char) ch);
    }
} catch (java.io.IOException e) {
    e.printStackTrace();
}

// Custom exception
class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}