简体   繁体   中英

Throwing checked exception similar to “IllegalArgumentException”

I have the following method where "a" is input from the user (network request to my service)

private ReturnObject getX(InputObject a) {
  ReturnObject ret = new ReturnObject();
  String s = a.getSomething();
  if (s != null) {
    ret.setSomething(s);
    return ret;
  }

  throws new CheckedExceptionSimilarToIllegalArgumentexception();
}

I'm calling this method internally so I'd like to handle the exception myself. In fact, I want to force everybody calling this method to handle this exception.

In my case, if the exception is thrown I want to catch it, inform the user that they did not set the appropriate field in the request & end the request.

I don't want to be returning nulls and then checking if the method returned null, that's really ugly.

However, I can't seem to find a checked exception similar to IllegalArgumentException and I don't want to create a new exception either. This seems like a very common scenario and I'm surprised I couldn't find anything.

I would suggest adding @NotNull to the input argument. This way a tool such as findbug or IntelliJ can warn you when you write the code not to pass a null value in the first place.

In that case, passing a null is a coding error, and I would throw an error to encourage developers to check the input before it is passed.

The problem with using checked exceptions is that too many developers ignore them. I am a fan of checked exceptions myself, but it only works when developers know how to handle exceptions.

Similarly, the problem with Optional is it's easy to ignore that Optional is not present and you don't get a message explaining why.

At some point you have to assume a developer will pick up they are using the API incorrectly and fix it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM