Documentation

The Java™ Tutorials
Hide TOC
The try Blocktry块
Trail: Essential Java Classes
Lesson: Exceptions
Section: Catching and Handling Exceptions

The try Blocktry块

The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block.构造异常处理程序的第一步是在try块中包含可能引发异常的代码。In general, a try block looks like the following:通常,try块如下所示:

try {
    code
}
catch and finally blocks . . .

The segment in the example labeled code contains one or more legal lines of code that could throw an exception.示例中标记为code的段包含一行或多行可能引发异常的合法代码。(The catch and finally blocks are explained in the next two subsections.)(在接下来的两小节中,将解释catch块和finally块。)

To construct an exception handler for the writeList method from the ListOfNumbers class, enclose the exception-throwing statements of the writeList method within a try block.要从ListOfNumbers类为writeList方法构造异常处理程序,请将writeList方法的异常引发语句包含在try块中。There is more than one way to do this.实现这一点的方法不止一种。You can put each line of code that might throw an exception within its own try block and provide separate exception handlers for each.您可以将可能引发异常的每一行代码放在它自己的try块中,并为每一行代码提供单独的异常处理程序。Or, you can put all the writeList code within a single try block and associate multiple handlers with it.或者,您可以将所有writeList代码放在一个try块中,并将多个处理程序与之关联。The following listing uses one try block for the entire method because the code in question is very short.下面的清单对整个方法使用了一个try块,因为所讨论的代码非常短。

private List<Integer> list;
private static final int SIZE = 10;

public void writeList() {
    PrintWriter out = null;
    try {
        System.out.println("Entered try statement");
        out = new PrintWriter(new FileWriter("OutFile.txt"));
        for (int i = 0; i < SIZE; i++) {
            out.println("Value at: " + i + " = " + list.get(i));
        }
    }
    catch and finally blocks  . . .
}

If an exception occurs within the try block, that exception is handled by an exception handler associated with it.如果try块中发生异常,则该异常由与其关联的异常处理程序处理。To associate an exception handler with a try block, you must put a catch block after it; the next section, The catch Blocks, shows you how.要将异常处理程序与try块关联,必须在其后面放置catch块;下一节,catch块,向您展示了如何使用它。


Previous page: Catching and Handling Exceptions
Next page: The catch Blocks