我可以避免这种繁琐的尝试......捕获块 [英] Can I avoid such cumbersome try...catch block

查看:81
本文介绍了我可以避免这种繁琐的尝试......捕获块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,在处理Java IO代码时,我写的是

Usually, when dealing with Java IO code, here is what I wrote

    FileOutputStream out = null;
    try
    {
        out = new FileOutputStream("myfile.txt");
        // More and more code goes here...
    }
    catch (Exception e)
    {
    }
    finally 
    {
        // I put the close code in finally block, to enture the opened
        // file stream is always closed even there is exception happened.
        if (out != null) {
            // Another try catch block, troublesome.
            try {
                out.close();
            } catch (IOException ex) {
            }
        }
    }

正如你所看到的,当我尝试关闭文件流时,我需要处理另一个try ... catch块。

As you can see, while I try to close the file stream, I need to deal with another try...catch block.

看起来很麻烦: (

我有什么办法可以避免吗?我把关闭代码放在非finally块中感觉不舒服,因为其他代码引起的异常会导致无效关闭被调用的机会。

Is there any way I can avoid? I don't feel comfortable in putting the close code in non-finally block, as exception caused by other codes will make no chance for "close" being called.

推荐答案

在finally中关闭流是非常重要的。你可以简化这个过程使用实用方法,例如:

It is very important that you close streams in a finally. You can simplify this process with a utility method such as:

public static void closeStream(Closeable closeable) {
    if(null != closeable) {
      try {
        closeable.close();
      } catch(IOException ex) {
        LOG.warning("Failed to properly close closeable.", ex);
      }
    }
  }

我认为它是LEA st记录流关闭失败。然后使用成为:

I make it a point of at least logging a stream close failure. The usage then becomes:

FileOutputStream out = null;
try
{
    out = new FileOutputStream("myfile.txt");
    // More and more code goes here...
}
catch (Exception e)
{
}
finally 
{
    closeStream(out);
}

在Java 7中,我相信流将自动关闭,需要这样块应该是多余的。

In Java 7 I believe that streams will be closed automatically and the need for such blocks should be mostly redundant.

这篇关于我可以避免这种繁琐的尝试......捕获块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆