Mil*_*n90 9 java exception try-catch try-catch-finally
"finally"和"catch"之后写的有什么区别?
例如:
public boolean example() {
try {
// Code
} catch (RuntimeException e) {
// Code
} finally {
return true;
}
}
public boolean example() {
try {
// Code
} catch (RuntimeException e) {
// Code
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
首先,唯一可以被视为候选人的成语是:
try {
// stuff
} catch (Throwable t) {
// handle
}
// finally stuff
Run Code Online (Sandbox Code Playgroud)
请注意捕获的类型.只有当你发现任何可能的例外,包括这种暗怪物ThreadDeath和VirtualMachineError能你希望无条件地达到在try-catch下面的代码.
但是,这只是它开始的地方.如果处理代码本身抛出异常怎么办?所以你至少需要
try {
// main stuff
} catch (Throwable t) {
try {
// handle
} catch (Throwable t) {
// no code allowed here! Otherwise we descend into
// infinite recursion
}
}
// finally stuff
Run Code Online (Sandbox Code Playgroud)
现在你可能已经开始意识到它的好处了finally,但并非全部.考虑一个非常典型的场景:
try {
// main stuff, may throw an exception. I want the exception to
// break what I'm doing here and propagate to the caller.
return true;
} finally {
// clean up, even if about to propagate the exception
}
Run Code Online (Sandbox Code Playgroud)
你怎么改写这个?没有代码重复,不可能.
你的情况没有区别。但
运行时系统始终执行finally 块中的语句,无论try 块中发生什么。
因此,它是进行清理的理想场所。
请注意,如果您使用的是 JDK 7+,则只需使用try-with-resources 语句即可消除大部分的 finally 块的使用。
| 归档时间: |
|
| 查看次数: |
1542 次 |
| 最近记录: |