抓住上层阶级的异常是我想知道的。我有多个方法调用层。在最深层次,抛出异常。在顶层我怎么能抓住?
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
}
答案 0 :(得分:3)
如Java documentation中所述,Exception
被调用堆栈中的第一个异常处理程序( try / catch 块)捕获,该异常处理程序可以处理抛出的异常类型
如果您未在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
如果您未在gbr
或bar
中定义异常处理程序,则必须指定两个方法抛出异常,这些异常可以处理在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()。