关于序列化:为什么Java在Exception和Throwable类中声明了serialVersionUID?

why Java declared serialVersionUID in Exception and Throwable class?

当我像下面一样创建一个自定义异常类时

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class MyApppException extends Exception {

    private String message = null;

    public MyApppException() {
        super();
    }
    public MyApppException(String message) {
        super(message);
        this.message = message;
    }
    public MyApppException(Throwable cause) {
        super(cause);
    }
}

编译器给了我下面的waning

The serializable class InsufficientBalanceException does not declare a static final serialVersionUID field of type long

从Java文档中,我理解了SerialValueUID的含义

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named"serialVersionUID" that must be static, final, and of type long:

但我不明白为什么Java声明异常的SerialValueUID和可抛出类?serialversionID在exception和throwable类中的用途是什么?真的需要吗?如果是,为什么?有人请澄清。

例外

1
2
public class Exception extends Throwable {
    static final long serialVersionUID = -3387516993124229948L;

可抛出

1
2
3
public class Throwable implements Serializable {
    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -3042686055658047285L;


自定义的异常可以有一个状态(=实例变量),它们可以是您希望在异常中记录的附加信息。状态就是被序列化的。并且,您可以在创建应用程序的新版本时更改状态(对于ExMaple,添加新变量),因此加载序列化异常的类需要知道它加载的版本是否与JVM的类定义兼容。