站内搜索: 请输入搜索关键词
当前页面: 在线文档首页 > Java Tutorial 5.0 英文版

Exception-Handling Statements - Java Tutorial 5.0 英文版

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

Trail: Learning the Java Language
Lesson: Language Basics

Exception-Handling Statements

The Java programming language provides a mechanism known as exceptions (in the glossary) to help programs report and handle errors. When an error occurs, the program throws an exception. What does this mean? It means that the normal flow of the program is interrupted and that the runtime environment attempts to find an exception handler—a block of code that can handle a particular type of error. The exception handler can attempt to recover from the error or, if it determines that the error is unrecoverable, provide a gentle exit from the program.

Three statements play a part in handling exceptions:

  • The try (in the glossary) statement identifies a block of statements within which an exception might be thrown.
  • The catch (in the glossary) statement must be associated with a try statement and identifies a block of statements that can handle a particular type of exception. The statements are executed if an exception of a particular type occurs within the try block.
  • The finally (in the glossary) statement must be associated with a try statement and identifies a block of statements that are executed regardless of whether or not an error occurs within the try block.

Here's the general form of these statements.

try {
    statement(s)
} catch (exceptiontype name) {
    statement(s)
} finally {
    statement(s)
}
This is a brief overview of the statements used in reporting and handling errors. However, other factors and considerations — such as the difference between runtime and checked exceptions and the hierarchy of exceptions classes, which represent various types of exceptions — play a role in using the exception mechanism. The chapter Handling Errors Using Exceptions (in the Learning the Java Language trail) provides a complete discussion of this subject.

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.