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;
}
最佳答案
首先,唯一可以被视为候选的成语是:
try {
// stuff
} catch (Throwable t) {
// handle
}
// finally stuff
注意捕获的类型。只有捕捉到任何可能的异常,包括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
现在您可能开始意识到 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
}
你如何重写这个?没有代码重复,这是不可能的。
关于java - finally 和 write after catch 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17261843/