从toString方法引发异常 [英] Throwing exception from toString method

查看:390
本文介绍了从toString方法引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java类pojo,在其中我希望Object.toString()方法返回该对象的JSON表示形式。 toString()的用户仅需要JSON。这是我的toString()。

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.

但是, toString()不允许我们引发异常。因此,我们只能抛出未经检查的异常。
上面链接的选定答案是从toString()抛出异常是一个非常糟糕的主意。它建议返回一个错误字符串,这对我来说似乎很糟糕,因为我们实际上只是在吞没异常。另一个建议是改为抛出IllegalStateExcception。这是在这种情况下抛出的理想例外,还是我们应该抛出另一种例外?谢谢。

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.

更新:我更正了我的代码中的一个错误。 toString()方法不带参数。

UPDATE : I corrected a mistake in my code. The toString() method does not take a parameter.

推荐答案

我也建议不要从 toString 。该方法通常用于调试目的(无论是通过 System.out 还是与调试器一起使用)。抛出异常只会使事情变得复杂,并使一切变得更困难。

I would also advise against throwing an exception from toString. The method is often used for debugging purposes (whether its via System.out or with a debugger). Throwing excpetions just complicates things and makes everything harder.

相反,我建议添加一个 toJSON 方法JsonProcessingException或RuntimeException的子类,并实现toString,以使其调用toJson,捕获所有异常并在这种情况下返回错误消息。

Instead, I would suggest to add a toJSON method that throws either a JsonProcessingException or a (subclass of) RuntimeException, and implement toString such that it calls toJson, catches all exceptions and returns the error message in such cases.

这篇关于从toString方法引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆