问题描述
当try-catch结束时,总是会执行finally块,无论是否异常。
但是,try-catch之外和之后的每一行代码都会被执行。
那么,我为什么要使用finally语句呢?
The "finally" block is always executed when the try-catch ends, either in case of exception or not.But also every line of code outside and after the try-catch is always executed.So, why should I use the finally statement?
示例:
try {
//code...
} catch (Exception e) {
//code...
} finally {
System.out.println("This line is always printed");
}
System.out.println("Also this line is always printed !! So why to use 'finally'?? ");
推荐答案
最有用的情况是你需要释放一些资源:
The most useful case is when you need to release some resources :
InputStream is = ...
try {
//code...
} catch (Exception e) {
//code...
} finally {
is.close();
}
更一般地说,当你想确定你的代码被执行时,你会使用它最后,即使执行期间有异常:
More generally, you use it when you want to be sure your code is executed at the end, even if there was an exception during execution :
long startTime = System.currentTimeMillis();
try {
//code...
} catch (Exception e) {
//code...
} finally {
long endTime = System.currentTimeMillis();
System.out.println("Operation took " + (endTime-startTime) + " ms");
}
这个的想法终于
阻止始终执行是因为整个区块后面的第一行不是这种情况
The idea of this finally
block always being executed is that it's not the case for the first line following the whole block
- 如果
catch
块允许一些throwable传递 - 如果它重新抛出一个异常,这是非常频繁的
- if the
catch
block lets some throwable pass - if it rethrows itself an exception, which is very frequent
这篇关于使用“最后”的好处是什么?在java中的try-catch块之后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!