Lesson 11 of 12 · 9 min · Exceptions
Exceptions: checked, unchecked and try-with-resources
What you will learn
- The
Throwable,ErrorandExceptionhierarchy - Checked versus unchecked exceptions and when each is used
try,catch,finally, multi-catch andthrowversusthrowstry-with-resourcesandAutoCloseable- Read a stack trace
In simple words
When something goes wrong, like a missing file, a bad number or a lost network connection, Java does not carry on silently. It "throws" an exception, a message object that travels up through the code looking for someone to handle it. If nobody does, the program stops and prints where it happened. A try/catch block is you saying, "if that goes wrong, do this instead".
Words to know
- Exception: an object that describes something that went wrong.
- Throw: raise an exception.
- Catch: handle an exception in a
catchblock. - Stack trace: the printed list of method calls that led to the exception.
The hierarchy
Throwable
├── Error (serious JVM problems: OutOfMemoryError, StackOverflowError; do not catch)
└── Exception
├── (checked) IOException, SQLException, InterruptedException, ...
└── RuntimeException (unchecked)
├── NullPointerException
├── IllegalArgumentException
├── IllegalStateException
├── IndexOutOfBoundsException
├── ArithmeticException
└── ClassCastException
Checked versus unchecked
| Checked | Unchecked | |
|---|---|---|
| Class | Exception but not RuntimeException |
RuntimeException and its subclasses (and Error) |
| Compiler | forces you to catch or declare it | does not force you |
| Meant for | recoverable conditions outside your control: file missing, network down, database unavailable | programming errors: null where a value is required, bad argument, wrong state |
| Examples | IOException, SQLException |
NullPointerException, IllegalArgumentException |
public String readFirstLine(String path) throws IOException { // declares it
try (BufferedReader r = Files.newBufferedReader(Path.of(path))) {
return r.readLine();
}
}
The rule of thumb from the Java documentation: if a client can reasonably be expected to recover, make it a checked exception; if the client cannot do anything about it (a bug), make it unchecked. Modern frameworks such as Spring and JPA mostly use unchecked exceptions, because forced catch blocks that just rethrow are noise; checked exceptions are still the norm in the JDK's I/O and JDBC APIs.
try, catch, finally
try {
int n = Integer.parseInt(text);
System.out.println(100 / n);
} catch (NumberFormatException e) {
System.out.println("not a number: " + text);
} catch (ArithmeticException e) {
System.out.println("cannot divide by zero");
} finally {
System.out.println("always runs"); // cleanup, whether or not there was an exception
}
- Catch the most specific exception first; a broader catch placed before a narrower one will not compile.
- Multi-catch handles several types the same way:
catch (IOException | SQLException e). finallyruns even after areturnor an uncaught exception (except if the JVM exits). Do notreturnfromfinally: it hides exceptions.- Never swallow exceptions: an empty
catchblock hides bugs. At minimum, log the exception with its stack trace, or rethrow. - Avoid
catch (Exception e)orcatch (Throwable t)except at the outermost boundary of an application (a web request handler) where you log and return an error.
throw and throws
throw new IllegalArgumentException("age must be positive")raises an exception.throws IOExceptionin a method signature declares that the method may raise a checked exception, so callers must catch or declare it.
public void setAge(int age) {
if (age < 0) throw new IllegalArgumentException("age must be >= 0: " + age);
this.age = age;
}
Throw exceptions with helpful messages (what was wrong, with the bad value). Validate arguments early and fail fast. Objects.requireNonNull(x, "x must not be null") is the standard null check. Prefer standard exceptions (IllegalArgumentException, IllegalStateException, UnsupportedOperationException, NoSuchElementException) before inventing your own.
try-with-resources
Anything that must be closed (files, streams, database connections, sockets) should be opened in a try-with-resources: Java closes it automatically, in reverse order, even if an exception occurs.
try (var in = new FileInputStream("data.txt");
var out = new FileOutputStream("copy.txt")) {
in.transferTo(out);
} // out and in are closed here, automatically
The resource must implement AutoCloseable (or Closeable). You can also use an existing effectively final variable: try (conn) { ... }. Compare the old way, which was long and easy to get wrong:
FileInputStream in = null;
try {
in = new FileInputStream("data.txt");
// ...
} finally {
if (in != null) {
try { in.close(); } catch (IOException ignored) {}
}
}
If both the body and close() throw, the body's exception is the main one and the close() exception is attached as a suppressed exception (e.getSuppressed()), so you do not lose the real cause. Write your own resource by implementing AutoCloseable:
class Timer implements AutoCloseable {
private final long start = System.nanoTime();
@Override public void close() {
System.out.println("took " + (System.nanoTime() - start) / 1_000_000 + " ms");
}
}
try (var t = new Timer()) { /* work */ }
Reading a stack trace
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "name" is null
at com.shop.CustomerService.validate(CustomerService.java:27)
at com.shop.CustomerService.register(CustomerService.java:14)
at com.shop.Main.main(Main.java:8)
Read from the top: the exception type and message, then the method where it happened (validate, line 27), then who called it. (Helpful NPE messages, shown above, are on by default since Java 15.) Your own code's first line is usually where to start. With wrapped exceptions, look for Caused by: lines at the bottom: the root cause is the last one.
Other things to know
- Chaining: wrap and keep the cause:
throw new OrderException("could not save order " + id, e);so the original exception stays visible. - Rethrow with
throw e;or wrap; log once, where you handle it, not at every layer. InterruptedException: when you catch it, restore the flag (Thread.currentThread().interrupt()) unless you are ending the thread.- Do not use exceptions for normal control flow: checking
if (list.isEmpty())is better than catchingIndexOutOfBoundsException. Exceptions are slow to create (stack trace capture). Optionaland return values (a result type) often replace "not found" exceptions in your own APIs.
Common mistakes
- Empty
catchblocks. - Catching
ExceptionorThrowabletoo broadly. - Forgetting to close resources (use try-with-resources).
- Returning from
finally. - Losing the cause when wrapping (
throw new X(e.getMessage())instead ofthrow new X(msg, e)). - Using exceptions for normal flow.
- Logging and rethrowing at every layer, producing duplicate log lines.
Try it yourself
- Write a method that parses an integer and returns a default for bad input, catching the specific exception.
- Read a file with try-with-resources and test the missing-file case.
- Write a class that implements
AutoCloseable, use it in try-with-resources and check the closing order with two resources. - Produce a stack trace with
Caused by:, and identify the root cause.
Check yourself
What is the difference between a checked and an unchecked exception?
A checked exception must be caught or declared with throws, and signals recoverable external conditions; an unchecked exception (RuntimeException and subclasses) does not need to be declared and signals programming errors.
What does finally do?
It runs after the try and catch blocks whether or not an exception happened, used for cleanup.
Why prefer try-with-resources?
It closes resources automatically in reverse order, even on exceptions, and keeps suppressed close exceptions, with far less code than finally.
What is the difference between throw and throws?
throw raises an exception object; throws is part of a method's signature that declares which checked exceptions it may raise.
Interview questions
Can you have a try without catch?
Yes, with finally, or as try-with-resources, which needs neither catch nor finally.
What happens if both the try block and close() throw exceptions in try-with-resources?
The exception from the try block is thrown, and the one from close() is added as a suppressed exception, available through getSuppressed().
Is finally always executed?
Almost always: it runs after a return or an exception, but not if the JVM exits (System.exit), crashes or the thread is killed.
Summary
ErrorandExceptionextendThrowable; checked exceptions are enforced by the compiler, unchecked are not.- Catch specific exceptions, never swallow them, and keep the cause when wrapping.
- Use try-with-resources for anything closeable; read stack traces from the top and find the root cause.
- Validate early with standard exceptions and clear messages.
Going deeper
- dev.java: Exceptions: the official guide.
- The Java Tutorials: Exceptions: catch or specify, checked and unchecked.
- The try-with-resources statement:
AutoCloseableand suppressed exceptions. - Unchecked Exceptions: the controversy: when to use each kind.
See how much of this you can explain
A free mock interview asks you new questions on Core Java: OOP, collections and exceptions for Java Full Stack Developer and scores every answer, with what to fix.