A throws clause is used to declare any checked exceptions (§11.2) that can result from the execution of a method or constructor:
Throws:
throws
ClassTypeList ClassTypeList:
ClassType
ClassTypeList,
ClassType
A compile-time error occurs if any ClassType mentioned in a throws
clause is not
the class Throwable
(§20.22) or a subclass of Throwable
. It is permitted but not
required to mention other (unchecked) exceptions in a throws
clause.
For each checked exception that can result from execution of the body of a method or constructor, a compile-time error occurs unless that exception type or a superclass of that exception type is mentioned in a throws
clause in the declaration of the method or constructor.
The requirement to declare checked exceptions allows the 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 will normally result in a compile-time error because of the lack of a proper exception type in a throws
clause. Java thus encourages a programming style where rare and otherwise truly exceptional conditions are documented in this way.
The predefined exceptions that are not checked in this way are those for which declaring every possible occurrence would be unimaginably inconvenient:
Error
, for example OutOfMemoryError
, are thrown due to a failure in or of the virtual machine. Many of these are the result of linkage failures and can occur at unpredictable points in the execution of a Java program. Sophisticated programs may yet wish to catch and attempt to recover from some of these conditions.
RuntimeException
, for example NullPointerException
, result from runtime integrity checks and are thrown either directly from the Java program or in library routines. It is beyond the scope of the Java language, and perhaps beyond the state of the art, to include sufficient information in the program to reduce to a manageable number the places where these can be proven not to occur.
A method that overrides or hides another method (§8.4.6), including methods that implement abstract
methods defined in interfaces, may not be declared to throw more checked exceptions than the overridden or hidden method.
More precisely, suppose that B is a class or interface, and A is a superclass or superinterface of B, and a method declaration n in B overrides or hides a method declaration m in A. If n has a throws
clause that mentions any checked exception types, then m must have a throws
clause, and for every checked exception type listed in the throws
clause of n, that same exception class or one of its superclasses must occur in the throws
clause of m; otherwise, a compile-time error occurs.
See §11 for more information about exceptions and a large example.