java 。尝试关闭所有连接的有效方法是什么?

标签 java error-handling io try-catch ioexception

<分区>

例如,我有处理输入/输出流的方法:

    public void doSomethingWithStreams () throws FileNotFoundException, IOException
            {
             OutputStream out1, out2;            
             InputStream in1, in2;
try{                     
            //do something with Streams: read, write, process, etc.
            }
finally{
        //There I try to close connections
        out1.close();
        out2.close();
        in1.close();
        in2.close();
        }    
            }

方法可以抛出 IOException,这是有效的行为。 但是如果我在这一行中有异常:

 out1.close();

其他三个 Stream 将NOT 关闭。 你能推荐什么解决方案?如何? 全部有多近?

我只有一个:

    public void doSomethingWithStreams () throws FileNotFoundException, IOException
            {
             OutputStream out1, out2;            
             InputStream in1, in2;
         try{            
            //do something with Streams: read, write, process, etc.
            }
finally{
        //There I try to close connections

try{out1.close();}
  finally{
     try{out2.close();}
         finally{
            try{in1.close();}
                finally{
        in2.close();}
}}

}

            }

如您所见 - 我的方法是使用多个 try-finally block 。

你认为这是个好主意吗?

最佳答案

如果三个流不相互依赖,则每个流的 try/catch 看起来更干净。

类似于:

try{
 out1.close();
}catch(Exception e)
{
....
}finally

{....

try{
        out2.close();
}catch(Exception e)
{
.....
}finally

{....

编辑:正如 iccthedral 所建议的,如果您使用 Java7,则可以使用 try-with-resource block 。

关于 java 。尝试关闭所有连接的有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12372879/

相关文章:

java - 无法添加任务 ':jacocoTestReport',因为同名任务已存在

Angular 6 + RxJs - concatMap 的错误处理

macos - Prolog错误的编译?

perl - 将 select(2) 和文件句柄的缓冲 IO 结合起来是否安全?

performance - IO分析工具?

java - 使用 AES 在 Java 和 Python 中加密/解密

java - 在 Groovy 中编码时, "->"lamda 运算符有什么问题?

Java 对象到 JSON 对象

python - 错误处理 : Boto: [Error 104] Connection Reset by Peer

python Pandas : read file skipping commented