The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Essential Java Classes
Lesson: Handling Errors with Exceptions

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 (in the Essential Java Classes trail) 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 (in the Essential Java Classes trail) talks about specifying the 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 Unchecked Exceptions — The Controversy (in the Essential Java Classes trail) talks about when itís appropriate to use runtime exceptions.

Exceptions that can be thrown within the scope of the method
The exceptions that a method can throw include
  • Any exception thrown directly by the method with the throw statement
  • Any exception thrown indirectly by calling another method that throws an exception

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.