以下用于文件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块中,您正在使用in.close()语句关闭流。该语句还会引发IOException
您可以通过向这些close语句添加try/catch块来避免此异常。

10-07 18:59
查看更多