A throws clause is used to declare any checked exception classes (§11.1.1) that the statements in a method or constructor body can throw (§11.2.2).
Throws:
throws ExceptionTypeList
ExceptionTypeList:
ExceptionType {, ExceptionType}
ExceptionType:
ClassType
TypeVariable
It is a compile-time error if an ExceptionType mentioned in a throws clause is not a subtype (§4.10) of Throwable.
Type variables are allowed in a throws clause even though they are not allowed in a catch clause (§14.20).
It is permitted but not required to mention unchecked exception classes (§11.1.1) in a throws clause.
The relationship between a throws clause and the exception checking for a method or constructor body is specified in §11.2.3.
Essentially, for each checked exception that can result from execution of the body of a method or constructor, a compile-time error occurs unless its exception type or a supertype of its exception type is mentioned in a throws clause in the declaration of the method or constructor.
The requirement to declare checked exceptions allows a Java compiler to ensure that code for handling such error conditions has been included. Methods or constructors that fail to handle exceptional conditions thrown as checked exceptions in their bodies will normally cause compile-time errors if they lack proper exception types in their throws clauses. The Java programming language thus encourages a programming style where rare and otherwise truly exceptional conditions are documented in this way.
The relationship between the throws clause of a method and the throws clauses of overridden or hidden methods is specified in §8.4.8.3.
Example 8.4.6-1. Type Variables as Thrown Exception Types
import java.io.FileNotFoundException;
interface PrivilegedExceptionAction<E extends Exception> {
void run() throws E;
}
class AccessController {
public static <E extends Exception>
Object doPrivileged(PrivilegedExceptionAction<E> action) throws E {
action.run();
return "success";
}
}
class Test {
public static void main(String[] args) {
try {
AccessController.doPrivileged(
new PrivilegedExceptionAction<FileNotFoundException>() {
public void run() throws FileNotFoundException {
// ... delete a file ...
}
});
} catch (FileNotFoundException f) { /* Do something */ }
}
}