尽管捕获了IOException,但编译器错误

ank*_*981 2 java exception

以下文件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();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我评论了这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
Run Code Online (Sandbox Code Playgroud)

当我包含throws IOException零件时,错误消失了,但我很困惑.我抓住异常是不够的?

Era*_*ran 6

您没有捕获可能在您的finally块中抛出的潜在IOException.

您可以通过向finally块添加try-catch来修复它:

    finally
    {
      try {
        if (in != null)
        {
            in.close();
        }
        if (out != null)
        {
            out.close();
        }
      }
      catch (IOException ex) {
      }
    }
Run Code Online (Sandbox Code Playgroud)