What is the difference between throw and throws in Java, and how does the compiler use each one?
They look almost the same, but one of them throws an exception and the other one only promises that you might.
The statement throw actually throws an exception. It takes an exception object and hands it to the runtime, which then looks for a catch block that matches it.
The keyword throws is part of the signature of a method. It lists the checked exceptions that the method may let pass on to its caller. It does not throw anything by itself, it only tells the compiler what to expect.
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
readFile("data.txt");
} catch (IOException e) {
System.out.println("could not read the file : " + e.getMessage());
}
// This one really throws.
throw new IllegalStateException("the program cannot go on");
}
// The throws clause says that this method may pass this failure on.
// It does not throw anything by itself.
static void readFile(String name) throws IOException {
if (name.isEmpty()) {
throw new IOException("no file name was given");
}
}
}
So how does the compiler use each one? It uses throws to decide whether you have to deal with a call. If a method says that it may throw an IOException, then every caller has to catch that or declare it in its own signature. The throw statement is what actually happens at run time when the condition is met.
One detail is worth knowing. A method may throw any unchecked exception without saying so, because the compiler does not ask you to declare those. So a throws clause only ever needs to list the checked exceptions.
The next question in this topic looks at listing more than one of them.