欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

The try Block

程序员文章站 2022-07-12 22:55:08
...

The try Block

The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block. 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. (The catch and finally blocks are explained in the next two subsections.)

在例子中被标记为code的代码段包含可能会抛出异常的一行或多行代码。(catchfinally语句块将会在下两个子节中被说明。)

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. 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. Or, you can put all the writeList code within a single try block and associate multiple handlers with it. The following listing uses one try block for the entire method because the code in question is very short.

为了给ListOfNumbers类中的writeList方法构造一个异常处理器,将writeList方法中的异常抛出语句使用try语句块围起来。这里有不止一种方式可以做到。你可以把可能会抛出异常的每一行放到它自己的try语句块中并为它提供单独的异常处理器。或者你能把writeList方法中的所有代码放到一个单一的try语句块中,并给它关联多个处理器。下面的代码清单中,对于整个方法使用了一个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. 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语句块里面,异常将会被关联的异常处理器所处理。为了将异常处理器与try语句块关联,你必须在try语句块后放一个catch语句块;在下一节The catch Blocks中将会为你展示如何使用catch语句块。