Skip to main content
Exception handling · Topic 2 of 7

Checked vs unchecked

Definition​

A checked exception must be caught or declared with throws, so the compiler makes you deal with it. An unchecked exception (a RuntimeException) needs no declaration and usually means a bug in the code.

Example code​

Reading a missing file (checked) and bad input (unchecked)

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

class Demo {
// IOException is checked: the method must declare it
static String readFile(String name) throws IOException {
return Files.readString(Path.of(name));
}

// IllegalArgumentException is unchecked: no declaration needed
static int percent(int part, int whole) {
if (whole == 0) throw new IllegalArgumentException("whole must not be zero");
return part * 100 / whole;
}

public static void main(String[] args) {
try {
readFile("missing.txt");
} catch (IOException e) {
System.out.println("Could not read: " + e.getClass().getSimpleName());
}
try {
percent(1, 0);
} catch (IllegalArgumentException e) {
System.out.println("Bad input: " + e.getMessage());
}
}
}

// Output:
// Could not read: NoSuchFileException
// Bad input: whole must not be zero

Finished this page? Track your progress (saved only in your browser).