捕获上层方法中从最深层调用抛出的异常

时间:2014-08-10 12:06:32

标签: java

抓住上层阶级的异常是我想知道的。我有多个方法调用层。在最深层次,抛出异常。在顶层我怎么能抓住?

void foo() {
   bar(); <---- catch exception in here
}

void bar() {
   // .... <--- throws IOException or ExecutionException or InterruptedException
}

OR case two


void foo() {
   bar(); <---- catch exception in here
}

void bar() {
   gbr();
}

void gbr() {
      // .... <--- throws IOException or ExecutionException or InterruptedException
}

2 个答案:

答案 0 :(得分:3)

异常处理

Java documentation中所述,Exception被调用堆栈中的第一个异常处理程序( try / catch 块)捕获,该异常处理程序可以处理抛出的异常类型

Exception handling

<案例1

如果您未在bar中定义异常处理程序( try / catch 块),则需要指定方法抛出某些异常,可以由foo处理(在调用堆栈的上一步)。

void foo() {
    try {
        bar();
    } catch (IOException io) {
        // Do something
    } catch (ExecutionException ee) {
        // Do something
    } catch (InterruptedException ie) {
        // Do something
    }
}

void bar() throws IOException, ExecutionException, InterruptedException {
    // .... <--- throws IOException or ExecutionException or InterruptedException
}
<案例2

如果您未在gbrbar中定义异常处理程序,则必须指定两个方法抛出异常,这些异常可以处理在foo

void foo() {
    try {
        bar();
    } catch (IOException io) {
        // Do something
    } catch (ExecutionException ee) {
        // Do something
    } catch (InterruptedException ie) {
        // Do something
    }
}

void bar() throws IOException, ExecutionException, InterruptedException {
    gbr();
}

void gbr() throws IOException, ExecutionException, InterruptedException {
    // .... <--- throws IOException or ExecutionException or InterruptedException
}

一般情况

如果您不想区分抛出的异常,可以使用类Exception,它是所有异常(docs)的祖先,因此匹配所有异常:

void foo() {
    try {
        bar();
    } catch (Exception e) {
        // Do something
    }
}

void bar() throws Exception {
    // .... <--- throws IOException or ExecutionException or InterruptedException
}

答案 1 :(得分:0)

第一个相关的try / catch块将捕获抛出的异常。如果这样的块不存在,那么程序将因未处理的异常而崩溃。

因此,如果gbr()抛出一个未被捕获的异常,它将返回bar。如果bar()没有捕获它,那么它将返回foo()等,直到它返回main()。