Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my exception class needs to be serialized?

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?

like image 738
amod Avatar asked Oct 07 '11 06:10

amod


People also ask

Do exceptions need to be serializable?

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).

Why does a class need to be serializable?

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.

Why do objects need to be serialized?

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.

What does it mean for a class to be serialized?

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.


2 Answers

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.

like image 183
Sanjay T. Sharma Avatar answered Sep 21 '22 04:09

Sanjay T. Sharma


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.

like image 44
JB Nizet Avatar answered Sep 24 '22 04:09

JB Nizet