2

I have a use case where I want to return some data (an object) as I throw an exception. I'm considering storing the data in my custom checked exception class and accessing it via a getter when the exception is caught higher up in the stack. Is this considered a bad idea? If so what are some better alternatives? I've seen sending relevant messages to the customized exception but haven't really seen it being used as a data store.

I did stumble across Return a value AND throw an exception? and one of the answers there is doing something similar. I was thinking more along the lines of overloading the constructor and supplying the object instead of passing it as another argument. Is that considered bad coding practice?

  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;
    }
}
linuxNoob
  • 600
  • 2
  • 14
  • 30

1 Answers1

3

This is an established pattern.

For example, Spring's RestTemplate's HTTP request methods may throw a RestClientResponseException which has methods like byte[] getResponseBodyAsByteArray(), String getResponseBodyAsString(), HttpHeaders getResponseHeaders(),String getStatusText() and so on.

slim
  • 40,215
  • 13
  • 94
  • 127
  • As a follow up, does it make sense to add null checks on the parameters passed into the custom exception? The API you referred to doesn't seem to be doing it other than just stating which fields are nullable. – linuxNoob Oct 23 '17 at 16:15
  • Add null checks where? It's the throwing code's responsibility to populate any fields that may not be null. If you trust that code, you don't need to add code to check. Depends how defensive you want to be. – slim Oct 23 '17 at 16:19
  • Null checks for the formal arguments passed to the constructor so `externalService` in the example in my post. – linuxNoob Oct 23 '17 at 19:52
  • 1
    It's a broad question. See this answer https://stackoverflow.com/a/2999417/7512 (and the other answers to the same question -- but I'm not sure the poster has chosen the right answer). I never check for null parameters - it can throw a NullPointerException downstream, and serves the caller right. – slim Oct 24 '17 at 09:22