1. 程式人生 > >Java 日看一類(39)之IO包中的ObjectStreamException和OptionalDataException異常類

Java 日看一類(39)之IO包中的ObjectStreamException和OptionalDataException異常類

ObjectStreamException異常類繼承自IOException

該類的類頭註釋如下:

* Superclass of all exceptions specific to Object Stream classes.

大意如下:

描述所有物件流類異常的頂級類

該類含有如下的成員變數:

序列化ID

private static final long serialVersionUID = 7260898174833392607L;

該類含有如下的成員方法:

構造方法(傳入出錯的類名)

protected ObjectStreamException(String classname) {
    super(classname);
}

構造方法(預設)

protected ObjectStreamException() {
    super();
}

該類作為物件流異常的頂級類,一般情況下被使用到的是其子類,如下面要提到的OptionalDataException

OptionalDataException繼承自ObjectStreamException

該類的類頭註釋如下:

/**
 * Exception indicating the failure of an object read operation due to
 * unread primitive data, or the end of data belonging to a serialized
* object in the stream. This exception may be thrown in two cases: * * <ul> * <li>An attempt was made to read an object when the next element in the * stream is primitive data. In this case, the OptionalDataException's * length field is set to the number of bytes of primitive data
* immediately readable from the stream, and the eof field is set to * false. * * <li>An attempt was made to read past the end of data consumable by a * class-defined readObject or readExternal method. In this case, the * OptionalDataException's eof field is set to true, and the length field * is set to 0. * </ul> * * @author unascribed * @since JDK1.1 */

大意如下:

該類表示讀取物件操作失敗,原因是無法讀取流中物件的基本資料或者是序列化物件的末尾資料,該異常會因兩種原因被丟擲:

企圖讀取的物件下一部分是基礎資料,在這種情況下,OptionalDataException的長度欄位將會被設定為立刻可從流中讀出的基礎資料位元組數,檔案結束欄位為false

企圖使用類宣告的readObject或者readExternal方法來讀取資料末尾後的部分。在這種情況下,檔案結束欄位會被設定為true,並且長度欄位設定為0

該類含有如下的成員變數:

序列化ID

private static final long serialVersionUID = -8011121865681257820L;

可立刻被讀取出的byte長度

public int length;

檔案結束標誌符

public boolean eof;

該類含有如下的成員方法:

建構函式(第一種情況

OptionalDataException(int len) {
    eof = false;
length = len;
}

建構函式(第二種情況

OptionalDataException(boolean end) {
    length = 0;
eof = end;
}

該類的使用方式在註釋中已經提到,在這裡不再贅述(該類的註釋寫的有點模糊,說是資料末尾,又說是資料末尾後的非法空間,等到看到了該類的具體丟擲位置再來補充和更新)