Prefer try-with-resources to try
2018-08-04 本文已影响4人
空谷幽心
笔记
-
For example, in the firstLineOfFile method, the call to readLine could throw an exception due to a failure in the underlying physical device, and the call to close could then fail for the same reason. Under these circumstances, the second exception completely obliterates the first one.
try-finally中,如果finally里抛异常,会压抑掉try中的异常。 -
If exceptions are thrown by both the readLine call and the (invisible) close, the latter exception is suppressed in favor of the former.
try-with-resources中,情况相反,会记录并压抑close()中的异常。可以通过getSuppressed获取压抑住的异常信息。
理解与思考
- BufferedReader br = new BufferedReader(new FileReader(path))只需要关闭br即可。BufferedReader 会关闭关联的资源。
- 没找到方法验证例子中的样例代码。