将数据存储在自定义检查异常中是个坏主意吗?

Is it a bad idea to store data in a custom checked exception?

我有一个用例,我想在抛出异常时 return 一些数据(一个对象)。我正在考虑将数据存储在我的自定义检查异常 class 中,并在异常被捕获到堆栈的较高位置时通过 getter 访问它。这被认为是一个坏主意吗?如果是这样,有哪些更好的选择?我已经看到将相关消息发送到自定义异常,但还没有真正看到它被用作数据存储。

我确实偶然发现了 Return a value AND throw an exception?,那里的答案之一就是做类似的事情。我更多地考虑重载构造函数并提供对象而不是将其作为另一个参数传递。这被认为是糟糕的编码习惯吗?

  public class NameException extends Exception
{

    private static final long serialVersionUID = -4983060448714460116L;
    private Service externalService;


    public NameException(final String message)
    {
        super(message);
    }

    public NameException()
    {
    }

    public NameException(Service externalService)
    {
        this.externalService =externalService;
    }

    public Service getExternalService()
    {
      return externalService;
    }
}

这是一个既定的模式。

例如,Spring 的 RestTemplate 的 HTTP 请求方法可能会抛出一个 RestClientResponseException,其中包含 byte[] getResponseBodyAsByteArray() 等方法, String getResponseBodyAsString(), HttpHeaders getResponseHeaders()String getStatusText() 等等。