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.
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
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
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
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.