2010-07-13 28 views
1

下面是我使用的代碼:被錯誤我收到幫助第一序列化程序

public class Ser implements Serializable { 
int x,y; 
String name; 
public Ser(int a, int b, String c) { 
    x=a; 
    y=b; 
    name = c; 
    } 
} 

import java.io.*; 

public class testSer { 
public static void main(String[] args) { 
    FileOutputStream testStream = new FileOutputStream("serText.ser"); 
    ObjectOutputStream testOS = new ObjectOutputStream(testStream); 
    Ser objTest = new Ser(1,2, "Nikhil"); 
    testOS.writeObject(objTest); 
    testOS.close(); 
    } 
} 

這裏:

Errors http://i29.tinypic.com/2weauzt.jpg

我創建了* .ser文件手動在文件夾中(儘管本書說編譯器會自動創建一個),但問題仍然存在。

RELP!

回答

3

你沒有處理IOException。您需要捕捉它或明確地拋出它。

try{ 
    // Your code 
}catch(IOException e){ 
    // Deal with IOException 
} 

public static void main(String[] args) throws IOException{ 
    // Your code 
} 

這是有checked exceptions,其中IOException異常是一個Java的所有後果。

出於您的目的,第二個可能很好,因爲IO故障不能真正從中恢復。在較大的程序中,您幾乎可以肯定希望從瞬時IO故障中恢復,因此第一個更合適。

4

您需要以某種方式處理IOException,要麼捕獲它,要麼拋出main。對於一個簡單的程序,投擲可能是很好的:

public static void main(String[] args) throws IOException 
+1

要具體放在代碼周圍try/catch或指示主拋出IOException。您應該在IDE中進行開發(例如Eclipse(免費))。這樣做的好處是IDE會給你提供警告/錯誤,併爲這類問題提供解決方案。 – Syntax 2010-07-13 10:49:42

+0

它的工作,但爲什麼我需要拋出一個異常,如果我已經創建文件? – MoonStruckHorrors 2010-07-13 10:59:34

+2

你說你的程序*可以拋出異常。大多數情況下不會,但有各種可能的IO錯誤。例如,想象一下如果磁盤空間不足。 – 2010-07-13 11:41:45

1

您需要使用try/catch塊,處理在您正在使用的方法中聲明爲拋出的異常。閱讀exception handling將是值得的。