CKTIS / Java
Exceptions and error handling in Java
Exceptions and error handling in Java: Java reports failures as Throwable: Error normally represents JVM-level problems, Exception covers application conditions, and RuntimeException is unchecked.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
errorsJava reports failures as Throwable: Error normally represents JVM-level problems, Exception covers application conditions, and RuntimeException is unchecked.
Handle expected checked exceptions at I/O boundaries, use domain exceptions for contract violations, and close resources with try-with-resources.
Do not catch Throwable or Error as routine control flow; a catch should preserve the cause, and finally should not return or mask the original exception.
If close also fails, try-with-resources keeps the primary exception and records the close failure as suppressed; a specific catch must precede a broader one.
The body exception remains primary, while the close failure is suppressed, so the two lines read body and close.
Examples
import java.io.IOException;
public class Main {
static final class BrokenResource implements AutoCloseable {
@Override public void close() throws IOException {
throw new IOException("close");
}
}
public static void main(String[] args) {
try (var ignored = new BrokenResource()) {
throw new IllegalStateException("body");
} catch (Exception ex) {
System.out.println(ex.getMessage());
System.out.println(ex.getSuppressed()[0].getMessage());
}
}
}
Result
body close
The body exception remains primary, while the close failure is suppressed, so the two lines read body and close.