2011-12-18 99 views
1

我收到此错误:的Java IO捕获异常

bill value:$ 0.10 
bill value: $0.05 
bill value: $0.01 
bill value: $100.00 
Exception in thread "main" java.io.EOFException 
    at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source) 
    at java.io.ObjectInputStream.readObject0(Unknown Source) 
    at java.io.ObjectInputStream.readObject(Unknown Source) 
    at ReadMoney.main(ReadMoney.java:12) 

================== 我的代码:

//import java.util.Date; 
public class ReadMoney 
{ 
    public static void main(String argv[]) throws Exception 
    { 
     FileInputStream fis = new FileInputStream("money.out"); 
     ObjectInputStream ois = new ObjectInputStream(fis); 
     Object read; 
     try 
     { 
      while ((read = ois.readObject()) != null) 
      { 
       if (read instanceof Bill) 
       { 
        System.out.println("bill value: " + read); 
       } 
       else if (read instanceof Quarter) 
       { 
       }// while 
       else if (read instanceof Dime) 
       { 
        System.out.println("bill value:" + read); 
       } 
       else if (read instanceof Nickel) 
       { 
        System.out.println("bill value:" + read); 
       } 
       else if (read instanceof Penny) 
       { 
        System.out.println("bill value:" + read); 
       } 
       else if (read instanceof Bill) 
       { 
        System.out.println("bill value:" + read); 
       } 

      Money quarter = (Money) ois.readObject(); 
      System.out.println("Quarter: "+ quarter); 
      System.out.println("Quarter: "+ quarter); 
      Money dime = (Money) ois.readObject(); 
      System.out.println("Dime:" + dime); 
      Money nickel = (Money)ois.readObject(); 
      System.out.println("Nickel:" + nickel); 
      Money penny = (Money) ois.readObject(); 
      System.out.println("Penny:" + penny); 
      Money bill = (Money) ois.readObject(); 
      System.out.println("Bill: " + bill); 
     }// try 
     } catch (IllegalBillException ibe) 
     { 
      System.out.println("End of file reached"); 
     } 
     ois.close(); 
     fis.close(); 
    }// main 
}// class 

我我非常确定我的try和catch块是正确的,但是我的程序没有打印2个季度的值,并且出于某种奇怪的原因,文本也显示“达到文件结尾”。 =/

+0

你的文件的内容是什么?似乎它不包含你认为它的作用。 – Tudor 2011-12-18 21:17:49

回答

1

你正在捕捉IllegalBillException(不管那是什么),但你没有捕捉到EOFException(或它的超类,IOException)。

+0

哦,我看到谢谢!我错过了另一个捕获声明!感谢同胞们! – 2011-12-18 21:27:00

0

的问题是,你的while条件,测试对于与空检查EOF,没有“保护”东西“}// try”之后,因此在该点之后的readObject通话将试图读取超出EOF并获得例外。

你需要以某种方式重构你的逻辑。

捕获EOFException将使异常“消失”,但不会修复您的错误。

+0

感谢热舔!它现在已经修复了! :) – 2011-12-19 00:32:19