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

时间:2015-05-01 09:51:03

标签: 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();
            }
        }
    }
}

正如你所看到的,我评论了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部分时,错误消失了,但我很困惑。我抓住异常是不够的?

3 个答案:

答案 0 :(得分:6)

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

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

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

答案 1 :(得分:4)

在finally块中,您使用in.close()语句关闭流。此语句也会抛出IOException。 您可以通过向这些紧密语句添加try/catch块来避免此异常。

答案 2 :(得分:3)

为了不必报告异常,您需要将其放在try块的try/catch/finally部分中。未捕获catchfinally部分中引发的异常,从而提示编译器错误:

try {
    ... // Exceptions thrown from here will be caught
} catch (ExceptionOne e1) {
    .. // Exceptions thrown from here need to be declared
} catch (ExceptionTwo e2) {
    .. // Exceptions thrown from here need to be declared
} finally {
    .. // Exceptions thrown from here need to be declared
}