Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The Java runtime system requires that a method either catch or specify all checked exceptions that can be thrown by that method. This requirement has several components "catch," "specify," "checked exceptions," and "exceptions that can be thrown within the method's scope" that need further description.
- Catch
- A method can catch an exception by providing an exception handler for that type of exception. The Catching and Handling Exceptions section introduces an example program, talks about catching exceptions, and shows 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 Specifying the Exceptions Thrown by a Method section talks about specifying the exceptions a method throws and shows how to do it.
- Checked Exceptions
- There are two kinds of exceptions: runtime and nonruntime. Runtime exceptions occur within the Java runtime system: arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object抯 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抰 have to catch or specify them. In general, this is not recommended. The Unchecked ExceptionsThe Controversy section talks about when it's appropriate to use runtime exceptions.
- Exceptions that Can Be Thrown Within the Method's Scope
- The exceptions that a method can throw include the following:
- Any exception thrown directly by the method with the
throw
statement- Any exception thrown indirectly by calling another method that throws an exception
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.