I have a Java class pojo in which I want the Object.toString() method to return a JSON representation of the object. The users of toString() want JSON only. This is my toString().
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
@Override
public String toString(){
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = null;
try {
json = ow.writeValueAsString(this);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return json;
}
The problem is that the above code will swallow the exception and allow execution to continue. To avoid such problems, we can either throw exception or re-throw the exception as an unchecked exception as mentioned here Java - overriding Object's toString() method, but I have to throw exceptions.
But, toString() does not allow us to throw exceptions. So, we can only throw an unchecked exception. The above link's selected answer says that "throwing exceptions from toString() is a really bad idea". It suggests to return a error string instead which seems bad to me because we are really just swallowing the exception. The other suggestion is to throw IllegalStateExcception instead. Is this the ideal exception to throw in this situation or should we throw another one ? Thanks.
UPDATE : I corrected a mistake in my code. The toString() method does not take a parameter.