gpt4 book ai didi

java - 尽管捕获了 IOException 还是编译器错误

转载 作者:行者123 更新时间:2023-12-02 05:00:09 27 4
gpt4 key购买 nike

以下文件 I/O 程序取自标准 Oracle 文档:

//Copy xanadu.txt byte by byte into another file
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyBytes
{
public static void main(String[] args) //throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;

try
{
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("xanadu_copy.txt");
int c;

while((c = in.read()) != -1)
{
out.write(c);
}
}
catch (IOException e)
{
System.out.println("IO exception : " + e.getMessage());
}
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}
正如你所看到的,我注释掉了 throws IOException 部分,认为既然我在代码中捕获了它,一切都应该没问题。但我收到编译器错误:

CopyBytes.java:32: error: unreported exception IOException; must be caught or declared to be thrown
in.close();
^
CopyBytes.java:36: error: unreported exception IOException; must be caught or declared to be thrown
out.close();
^
2 errors

当我包含 throws IOException 部分时,错误消失了,但我很困惑。我捕获异常还不够吗?

最佳答案

您没有捕获可能在finally block 中抛出的潜在IOException。

您可以通过在finally block 中添加try-catch来修复它:

    finally
{
try {
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
catch (IOException ex) {
}
}

关于java - 尽管捕获了 IOException 还是编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29984724/

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