Command Palette

Search for a command to run...

Back to the lesson: Topic 7.3 — Checked vs Unchecked Exceptions
Core Java · Example 2 of 3

Which exceptions are checked?

Checked exceptions (subclasses of Exception but not RuntimeException) must be caught or declared with throws, and the compiler enforces it. Unchecked exceptions (RuntimeException, Error and their subclasses) need no declaration because they usually mean a bug or a broken environment.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write static boolean isChecked(Class<? extends Throwable> c) using RuntimeException.class.isAssignableFrom(c) and Error.class.isAssignableFrom(c). Test it on IOException.class, IllegalStateException.class and OutOfMemoryError.class.

02

Write a method int parsePositive(String s) that throws an unchecked IllegalArgumentException for a non-positive number and lets NumberFormatException pass through. Call it in main with "7", "-3" and "x", catching each problem and printing its simple class name and message.

03

Given static int lengthOf(String path) throws IOException { if (path.isEmpty()) throw new IOException("empty path"); return path.length(); }, sum the lengths of List.of("a.txt", "", "bb.txt") with forEach and a wrapping lambda, and print the wrapped message when it fails.

Explain it without notes

01

What is the difference between checked and unchecked exceptions, and how does Java decide which is which?

02

What does 'catch or declare' mean, and who enforces it?

03

When would you design an API to throw a checked exception, and when an unchecked one?

04

Why do checked exceptions cause trouble with lambdas, and how do you deal with it?

05

Why can't an overriding method throw a broader checked exception?

Which exceptions are checked?
Sign in to run this example in your browser.

Expected output

Exception                   checked
IOException                 checked
FileNotFoundException       checked
InterruptedException        checked
TimeoutException            checked
CloneNotSupportedException  checked
NullPointerException        unchecked
IllegalArgumentException    unchecked
NumberFormatException       unchecked
ClassCastException          unchecked
UncheckedIOException        unchecked
AssertionError              unchecked