Java io丑陋的try-finally块 [英] Java io ugly try-finally block

查看:139
本文介绍了Java io丑陋的try-finally块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有那么丑陋的方法来处理 close()异常来关闭两个流然后:

  InputStream in = new FileInputStream(inputFileName); 
OutputStream out = new FileOutputStream(outputFileName);

尝试{
copy(in,out);
} finally {
try {
in.close();
catch(Exception e){
try {
// event in.close failed,need to close out
out.close();
} catch(Exception e2){}
throw e; //并抛出'in'异常
}
}
out.close();





update:以上所有代码都在一个try-catch内,谢谢警告。



FINALLY(在答案后):

实用程序方法可以使用执行周围的成语(谢谢Tom Hawtin)。 / p>

解决方案

这是正确的idom(它工作正常):

  InputStream in = null; 
OutputStream out = null;
尝试{
in = new FileInputStream(inputFileName);
out = new FileOutputStream(outputFileName);
copy(in,out);
finally {
close(in);
close(out);


public static void close(Closeable c){
if(c == null)return;
尝试{
c.close();
} catch(IOException e){
//记录异常
}
}

这个工作正常的原因是在你最终代码完成之前抛出的异常抛出,只要你的finally代码本身不抛出异常或以其他方式异常终止。

编辑:从Java 7(和Android SDK 19 - KitKat)开始,现在有一个Try with resources语法来使这个更清晰。如何处理这个在这个问题


Is there a not so ugly way of treat the close() exception to close both streams then:

    InputStream in = new FileInputStream(inputFileName);
    OutputStream out = new FileOutputStream(outputFileName);

    try {
        copy(in, out);
    } finally {
        try {
            in.close();
        } catch (Exception e) {
            try {
                // event if in.close fails, need to close the out
                out.close();
            } catch (Exception e2) {}
                throw e; // and throw the 'in' exception
            }
        }
        out.close();
    }

update: All the above code is within one more try-catch, thanks for the warnings.

FINALLY (after the answers):

And a good utility method can be done using Execute Around idiom (thanks Tom Hawtin).

解决方案

This is the correct idom (and it works fine):

   InputStream in = null;
   OutputStream out = null;
   try {
       in = new FileInputStream(inputFileName);
       out = new FileOutputStream(outputFileName);
       copy(in, out);
   finally {
       close(in);
       close(out);
   }

  public static void close(Closeable c) {
     if (c == null) return; 
     try {
         c.close();
     } catch (IOException e) {
         //log the exception
     }
  }

The reason this works fine is that the exception thrown before you got to finally will be thrown after your finally code finishes, provided that your finally code doesn't itself throw an exception or otherwise terminate abnormally.

Edit: As of Java 7 (and Android SDK 19 - KitKat) there is now a Try with resources syntax to make this cleaner. How to deal with that is addressed in this question.

这篇关于Java io丑陋的try-finally块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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