gpt4 book ai didi

java - 我可以避免这种麻烦的 try...catch block 吗

转载 作者:太空狗 更新时间:2023-10-29 22:33:21 25 4
gpt4 key购买 nike

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

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

看起来很麻烦:(

有什么办法可以避免吗?我不太愿意将关闭代码放在非 finally block 中,因为由其他代码引起的异常将没有机会调用“关闭”。

最佳答案

在 finally 中关闭流非常重要。您可以使用实用方法简化此过程,例如:

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

我至少要记录一个流关闭失败。然后用法变为:

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

在 Java 7 中,我相信流将自动关闭,对此类 block 的需求应该是多余的。

关于java - 我可以避免这种麻烦的 try...catch block 吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3305405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com