Java的。(Java. What is the valid way try to close all connections? [duplicate])

编程入门 行业动态 更新时间:2024-10-27 09:48:33
Java的。(Java. What is the valid way try to close all connections? [duplicate])

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

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将不会关闭。 你可以推荐什么解决方案? 怎么样? 有多接近?

我只有一个:

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块。

你认为这是个好主意吗?

This question already has an answer here:

Proper way to close an AutoCloseable 1 answer

For example, I have method for working with input/output streams:

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(); } }

Method can throws IOException and it is valid behavior. But If I have Exception in this line:

out1.close();

others three Stream will be NOT closed. What solution can you recommend? How? How close all?

I have just one:

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();} }} } }

As you can see - my approach is using multiple try-finally blocks.

Do you think it is good idea?

最满意答案

如果三个流不相互依赖,可能会为每个流看起来更干净。

就像是:

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

{....}

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

{....}

编辑:如iccthedral建议,如果您使用Java7,您可以使用try-with-resource块。

If three streams are not dependent on each other, may be having try/catch for each stream look cleaner.

Something like:

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

{.... }

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

{.... }

EDIT: As iccthedral suggested, if you use Java7 you may use try-with-resource block.

更多推荐

本文发布于:2023-08-02 05:48:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1370985.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:valid   Java   close   duplicate   connections

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!