未报告的异常IOException;必须被抓住或宣布被抛出

时间:2016-04-05 17:13:37

标签: exception

我有一个问题,为什么java一直在抛出异常!流是问题吗?因为我处理了所有IOExceptionS!

  

[[jio0yh.java:12:错误:未报告的异常IOException;一定是   抓住或宣布被抛出]]>>

这是我得到的例外!

这是我的代码

import java.io.*;
public class jio0yh{

public static void main(String[]args){

 FileInputStream OD=null;

try{


   File f=new File("Binary.dat");

 OD= new FileInputStream(f);

byte[]b=new byte[(int)f.length()];

OD.read(b);

for(int i=0;i<b.length;i++)

System.out.println(b[i]);}catch(FileNotFoundException e){System.out.println
(e.getMessage());}

catch(IOException e){System.out.println(e.getMessage());OD.close();}

}}

1 个答案:

答案 0 :(得分:1)

OD.close();在你的IOException中,catch块也容易抛出另一个IOException。

你应该在finally块中包围最终的OD.close():

// ... Any previous try catch code
} finally {
    if (OD != null) {
        try {
            OD.close();
        } catch (IOException e) {
            // ignore ... any significant errors should already have been
            // reported via an IOException from the final flush.
        }
    }
}

有关更详细的说明,请参阅以下内容:

Java try/catch/finally best practices while acquiring/closing resources