Java 尽管捕获IOException,编译器仍出错
以下文件I/O程序取自标准Oracle文档:Java 尽管捕获IOException,编译器仍出错,java,exception,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 IOExcep
//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();
}
}
}
}
如您所见,我注释掉了抛出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
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
}
当我包含
抛出IOException
部分时,错误消失了,但我感到困惑。我捕获异常还不够吗?您没有捕获可能在finally块中抛出的潜在IOException
您可以通过将try catch添加到finally块来修复它:
finally
{
try {
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
catch (IOException ex) {
}
}
为了不必报告异常,您需要将其放入
try/catch/finally
块的try
部分。未捕获catch
和finally
部分中抛出的异常,提示编译器错误:
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
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
}
在finally块中,您使用
In.close()
语句来关闭流。此语句还抛出IOException
。
您可以通过在这些关闭语句中添加
try/catch
块来避免此异常。您是否查看了编译器所说的错误所在?提示:它不是in.read(c)
或out.write(c)
@immibis我在阅读了下面的答案后,现在得到了它。我真傻我的意思是。。。如中所示,文件名和行号,就在每个错误的开头。@immibis是的,我现在知道了。我想,我的想法是不正确的Dcatch(IOException ex){}
是个坏主意-如果发生异常,程序不会告诉您出了什么问题。至少放置ex.printStackTrace()
。@immibis在关闭流时,对于此异常,您无能为力。如果在某个日志文件中看到此堆栈跟踪,您会怎么做?然后堆栈跟踪会告诉您流无法关闭的原因。(例如,完整硬盘和缓冲的内容)