Java – When we need to serialize an exception

exceptionsjavaserialization

I have been developing in Java since 8 months, and I didn't face a case where I went to serialize an exception, I'm asking because I saw the serialVersionUID and how Eclipse advise to add it explicitly in the Exception class that you define. So, I think that every(or the majority) exception is being serialized and I don't know that, maybe because the framework or the language itself is handling this issue.

I know that serialization is needed when you need to transfer the object through the network or when you need to store it, and I get the idea that we actually serialize the exception when we save the logs/exception backtrace into for example, catalina.out file, am I correct? and what other use cases that may need to serialize the exception?

Best Answer

If you're going to serialize a class, it needs a serialVersionID.

Your exception classes should always be serializable. You have no idea where the exception might be used, and if it gets marshaled across an app domain, you may lose debugging information or even lose the entire exception altogether. Exceptions are intended to be usable anywhere, and if they're not serializable, you can't use them across app domains.

The same principles also apply to C# exceptions.