例如,我有处理输入/输出流的方法:
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 answerFor 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.
更多推荐
发布评论