Creating an exception transient in Java

I have a class that extends Exception and therefore needs to be Serializable. The exception class contains a field that is not Serializable, so I saw it as a transition. I understand that this means that the field cannot be restored if my class is saved. When at runtime my exceptions can be serialized / deserialized? (nb As far as I know, I do not write them to a database or file).

+4
source share
5 answers

Unless you explicitly serialize them yourself, I think you can safely assume that creating your temporary transition will not have any bad consequences.

In my opinion, the JVM does not serialize objects without being explicitly requested to do so, so if you do not expect the Exception class to be serialized by your application, I do not think you have a reason for concern.

I assume that if you are writing a library and therefore cannot know all the uses of your class, you might need to be a little more careful.

+7
source

If the exception propagates through RMI, an RPC infrastructure, or the like, this can cause problems. If you do not use such functions, you can make it transient.

+4
source

Your understanding is correct. Fields marked as transient are not considered part of the state of the object and are not deliberately taken into account when serializing the object and will not be restored when the object is deserialized again. Serialization occurs when you want to save an object and its state to disk or send an object over the network. As far as I know, serialization does not occur during normal program execution, unless you specify your program explicitly.

+2
source

You can define writeObject to raise an UnsupportedOperationException or NotSerializableException to ensure that this object will never be serialized.

+1
source

Yes, if you have temporary fields in your exception, transition fields cannot be restored if your object becomes serialized / deserialized.

However, in small applications it is unlikely that you will need to serialize / deserialize unless you serialize the exceptions yourself. But pay attention if you use any kind of β€œmagic” framework or JNDI or any cluster environment.

0
source

All Articles