AI Hints
Home›Java Tutorial›Checked and Unchecked, throw and Custom Exceptions, try-with-resources
Java · Lesson 94 of 120

Checked and Unchecked

Two families of exceptions.

⏱ 2 min read▶ Video at 1:59:06🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Java has two families of exceptions. Checked exceptions, that Java forces you to handle. And unchecked exceptions, that usually mean a bug in your code.

  • Two families
  • Checked: must handle
  • Unchecked: usually bugs

Two families

Checked exceptions are problems outside your control, like a missing file, or a network failure. Java makes you deal with them. Unchecked exceptions are usually mistakes, like a null, or a bad index. You fix them by fixing the code.

Checked

  • IOExceptionOutside your controlMust catch or declare

Unchecked

  • NullPointerExceptionUsually a bugFix the code

Java insists

Reading a file can fail, so read string throws an IO exception, which is checked. We didn't handle it. Run it. Java won't compile. It says the exception must be caught, or declared to be thrown.

Main.javajava
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
    public static void main(String[] args) {
        String text = Files.readString(Path.of("notes.txt"));
        System.out.println(text);
    }
}
Output
Main.java:5: error: unreported exception IOException; must be caught or declared to be
thrown
        String text = Files.readString(Path.of("notes.txt"));
                                      ^
1 error
error: compilation failed

Handling it

Wrapping the call in try, and catching IO exception, satisfies Java. The file doesn't exist. Run it. No crash. Instead, a friendly message, naming the missing file.

Main.javajava
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
    public static void main(String[] args) {
        try {
            String text = Files.readString(Path.of("missing.txt"));
            System.out.println(text);
        } catch (IOException e) {
            System.out.println("Could not read: " + e);
        }
    }
}
Output
Could not read: java.nio.file.NoSuchFileException: missing.txt

Catch or declare

For a checked exception, you have two choices. Catch it, with try and catch. Or declare it, by adding throws, and the type, to your method. Then the caller has to deal with it.

keyvalue
Catchtry { } catch (IOException e)
Declarevoid m() throws IOException
Uncheckedno rule, but avoid them
Base classesException, RuntimeException

Summary

Checked exceptions must be caught, or declared with throws. Unchecked ones usually mean a bug to fix. Next, throwing exceptions yourself.

Key takeaways
  • Checked: catch or declare
  • Unchecked: fix the bug
  • throws
Next up: throw and Custom Exceptions — signal your own problems