2011-12-18 97 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