Java Foundations·Objects that hold up

Exceptions without confusion

Catch only what you can recover from; let everything else carry context.

Beginner 13 min read Lesson 8 of 300 Challenge included
What you will be able to do
  • Do not use exceptions for ordinary control flow.
  • Wrap low-level exceptions in a domain exception with context.
  • Use try-with-resources for files and connections.

In plain English

Checked exceptions are part of a method signature; unchecked exceptions usually indicate programming errors. A catch block should either recover, translate or add context. Never swallow an exception with an empty catch.

ReadFile.javaJava
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public String readNotes(Path path) {
    try {
        return Files.readString(path);
    } catch (IOException error) {
        throw new IllegalStateException("Could not read " + path, error);
    }
}
Your turn

Translate an IOException

Medium

Catch an IOException while reading a path and throw an IllegalStateException with context.

JAVA · starter
try {
    return Files.readString(path);
} catch (IOException error) {
}
Check your understanding before moving on.
Knowledge checkQuestion 1

What does try-with-resources guarantee?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 8 of 300 · 0% of course