美文网首页
Prefer try-with-resources to try

Prefer try-with-resources to try

作者: 空谷幽心 | 来源:发表于2018-08-04 12:08 被阅读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获取压抑住的异常信息。

    理解与思考

    1. BufferedReader br = new BufferedReader(new FileReader(path))只需要关闭br即可。BufferedReader 会关闭关联的资源。
    2. 没找到方法验证例子中的样例代码。

    实践

    相关文章

      网友评论

          本文标题:Prefer try-with-resources to try

          本文链接:https://www.haomeiwen.com/subject/naapvftx.html