Exception
An Exception in Java is an object that represents an error or unexpected condition that disrupts normal program flow. Exceptions are thrown, caught, and can carry a message and a cause.
Exception hierarchy
Throwable
βββ Error β serious JVM problems (OutOfMemoryError, StackOverflowError)
βββ Exception
βββ IOException, SQLExceptionβ¦ β CHECKED exceptions
βββ RuntimeException β UNCHECKED exceptions
βββ NullPointerException
βββ IllegalArgumentException
βββ ClassCastException
βββ IndexOutOfBoundsException
Throwing and catching
public String readFile(String path) {
try {
return Files.readString(Path.of(path));
} catch (IOException e) {
throw new RuntimeException("Failed to read " + path, e);
}
}
Checked vs unchecked
- Checked (extends
Exceptionbut notRuntimeException) β compiler forces you tothrowsor catch. - Unchecked (extends
RuntimeException) β compiler doesn't require handling. Used for programming errors.
try-with-resources
try (var reader = Files.newBufferedReader(path)) {
// resource is auto-closed even if an exception is thrown
return reader.readLine();
}
Exception chaining
throw new BusinessException("order failed", ioException);
Always include the cause β losing the stack trace of the original problem is a common debugging nightmare.