Search code examples
javaexceptionserializationserialversionuid

If I change the base class that a Java Exception class extends, do I need to update the serialVersionUID value?


Consider the following Java exception classes:

public class BarException extends RuntimeException {
    // [...]
}

public class FooException extends BarException {
    private static final long serialVersionUID = -5322002268075295537L;

    // [...]
}

If I wish to update the inheritance hierarchy to remove BarException, such that FooException derives directly from RuntimeException, does this require a change to the serialVersionUID value?

// FooException with updated inheritance hierarchy
public class FooException extends RuntimeException {
    private static final long serialVersionUID = ???;

    // [...]
}

Solution

  • Given that the specification is unclear enough to cause confusion and debate, with no clear answer emerging, the only option left is to trust empirical evidence.

    Taking the examples from the question above, of FooException deriving from BarException deriving from RuntimeException, and then removing BarException from the inheritance chain, I put together a sample application to try serialization and de-serialization in various combinations.

    I get the following results:

    As long as I keep the serialVersionUID unchanged, I can successfully serialize and deserialize the original FooException as the updated FooException, and vice versa.

    The following caveats apply:

    • I am using JDK 1.5.0_07, and have not tried this on any other versions.
    • FooException has members of type int and Exception, which are successfully deserialized.
    • BarException adds no additional members to RuntimeException.