以下文件 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/