Why my exception class needs to be serialized?

江枫思渺然 提交于 2019-12-18 10:44:45

问题


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?


回答1:


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.




回答2:


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.




回答3:


Your only options are to either define serialVersionUID for every Exception type you define (the IDE can generate it for you) or suppress the warning.

You may find my earlier question explicit serialVersionUID considered harmful? relevant.



来源:https://stackoverflow.com/questions/7683739/why-my-exception-class-needs-to-be-serialized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!