Skip to content
Advertisement

Serial version uid in abstract exception class

I have a base custom exception class BaseException

public class BaseException extends RuntimeException {

}

and several custom exceptions that extends BaseException

public class CustomException extends BaseException {
 private static final long serialVersionUID = 3655655808021733968L;
}

I got a warning about serial version uid being not declared in the BaseException class. Is it needed in an abstract class? Is it a good practice? Is any way to get rid of the warning?

Advertisement

Answer

Yes, you need to define the serialVersionUID in an abstract class. Serialization serializes instance state, which usually means the non-static fields; any inherited state needs to be serialized along with the rest of the object’s state.

The fact that you don’t have fields in BaseException doesn’t mean you should skip the serialVersionUID.

Note that, contrary to popular belief, a serialVersionUID does not need to be based on a hash of the class’s name or structure. Only the default computed serial version UID does this, when the class does not define a serialVersionUID field explicitly. Normally, you can declare it as a simple number:

private static final long serialVersionUID = 1;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement