Java - overriding Object's toString() method, but I have to throw exceptions

后端 未结 6 1224
抹茶落季
抹茶落季 2020-12-20 17:53

I have run into an issue where I have to override Object\'s toString() method, but the original method doesn\'t throw any exceptions. However, I am using some generic code t

6条回答
  •  甜味超标
    2020-12-20 18:29

    So, There is a purpose for RuntimeException. Runtime exceptions are either Fatal errors, which cannot let users to continue, or those are very frequent operations like Arithmetic operation or say equals or hashcode. Consider a case if hashcode started throwing an exception called HashCalculationException. What will be the impact of it on the users of HashMap, every time they call get or put on Map they have to catch an exception. Moreover, the implementations of these functions that are provided with JDK are exception proof, in order to maintain the integrity with other JDK components, and JDK expects developer to maintain the same. Here it comes the answer to your first question.

    Now, Should you throw an unchecked exception? This is my take on it. As per the guideline, using toString for serialization of a Java object itself a bad idea. toString is supposed to be used by loggers, or any other one-way handlers, where what you print doesn't make any difference from the point of integrity. Imagine you started using output generated by toString instead of serialization, and wrote your own method for create a new object out of it. Your object is holding huge data. and you entered in a situation where your caller accidentally started printing the object in logs... Imagine the amount of String concatenations it would do, and performance hit you get.

    So my suggestion in such scenario would be Get rid of toString if it's used to serialization. Its not the purpose of that method. Create a separate method for the same. Its fairly easy to do the same, just like adding a new exception in the method signature, and then use it.

    You can always throw Unchecked exception and catch it later, but it's strongly discouraged. it defeat's the purpose. Unchecked exceptions are meant for avoiding, not catching

    More reference, please read our discussion about RuntimeException here - https://stackoverflow.com/a/58455577/4675277

提交回复
热议问题