When you extend a class with class Exception ( for creating new exception) you get a warning to have a serialVersionUID
. I know that serialVersionUID
plays an important role while serialization and deserialization, but when my Exception needs to be serialized? Can anyone give me a practical case in which I want my custom-exception class to have serialization and deserialization?
Exceptions should be serializable so that they can automatically be marshalled across application domains or threads. At a minimum, you should mark your custom exception as serializable and implement the four basic constructors shown below. (This example shows a custom exception type that has no custom data).
Implement the Serializable interface when you want to be able to convert an instance of a class into a series of bytes or when you think that a Serializable object might reference an instance of your class. Serializable classes are useful when you want to persist instances of them or send them over a wire.
Serialization allows the developer to save the state of an object and re-create it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions such as: Sending the object to a remote application by using a web service.
To serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java.
This is because the root class for all exceptions, Throwable
implements the Serializable
interface. All exceptions by default are serializable and that's a language design decision because the authors wanted exceptions to be capable of being sent across the wire without any special configuration.
If the base class is not serializable, you would have a difficult time conveying what exactly went wrong in case a remote method failed since you would have no control over the built in exception types.
If your custom exception is ever used in a distributed application (using RMI, Spring http-invoker, whatever) and can be thrown from a server method that is invoked from a remote client, then the exception will have to be serialized to cross the wire and go to the client.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With