The Catch or Specify Requirement

The Java runtime system requires that a method must either catch or specify all checked exceptions that can be thrown by that method. This requirement has several components that need further description: "catch," "specify," "checked exceptions," and "exceptions that can be thrown by that method."

Catch

A method can catch an exception by providing an exception handler for that type of exception. The section Catching and Handling Exceptions (page 246) introduces an example program, talks about catching exceptions, and shows you how to write an exception handler for it.

Specify

A method specifies that it can throw exceptions by using the throws clause in the method declaration. The section Specifying the Exceptions Thrown by a Method (page 255) talks about specifying exceptions that a method throws and shows you how to do it.

Checked exceptions

There are two kinds of exceptions: runtime exceptions and nonruntime exceptions. Runtime exceptions occur within the Java runtime system: arithmetic exceptions (such as dividing by zero), pointer exceptions (such as trying to access an object's members through a null reference), and indexing exceptions (such as trying to access an array element with an index that is too large or too small). A method does not have to catch or specify runtime exceptions, although it may.

Nonruntime exceptions are exceptions that occur in code outside of the Java runtime system. For example, exceptions that occur during I/O are nonruntime exceptions. The compiler ensures that nonruntime exceptions are caught or specified; thus, they are also called checked exceptions.

Some consider the fact that you do not have to catch or specify runtime exceptions a loophole in the exception-handling mechanism. Many programmers are tempted to use runtime exceptions instead of checked exceptions so that they don't have to catch or specify them. In general, this is not recommended. The section Runtime ExceptionsThe Controversy (page 260) talks about when it's appropriate to use runtime exceptions.

Exceptions that can be thrown by a method

The exceptions that a method can throw include

Категории