throws
Declares which checked exceptions a method may throw.
Available since: Java 1.0
Syntax
Type method() throws ExceptionType { … }Examples
A method passes IOException on to its caller:
String firstLine(Path file) throws IOException {
return Files.readAllLines(file).getFirst();
}
void main() {
try {
IO.println(firstLine(Path.of("missing.txt")));
} catch (IOException e) {
IO.println("Cannot read: " + e.getClass().getSimpleName());
}
}Output:
Cannot read: NoSuchFileExceptionNotes
Checked exceptions extend Exception but not RuntimeException: IOException, InterruptedException. They must be either caught or declared in throws, otherwise you get "unreported exception IOException; must be caught or declared to be thrown". Unchecked ones (IllegalArgumentException, NullPointerException) need not be declared.
main can also declare throws Exception — that is fine for short programs.
See also
- throw — Throws an exception and stops the method.
- try / catch / finally — Catches exceptions; finally always runs, and try-with-resources closes resources for you.
- Files.readString() — Reads a whole text file into one string.
Related recipes
In the tutorial
- Checked and unchecked exceptions — Checked and unchecked exceptions in Java — what the compiler requires, the throws clause, RuntimeException and wrapping exceptions.