简体   繁体   English

缺少强制输入时使用的最佳运行时异常是什么

[英]What is the best runtime exception to use when mandatory input is missing

I have service, a simple class that need to take input and run some business logic. 我有服务,这是一个简单的类,需要输入并运行一些业务逻辑。 Before executing this service, the user must set all the data. 在执行此服务之前,用户必须设置所有数据。 In general, it look like this: 通常,它看起来像这样:

public class TestService extends InnerServiceBase {

    /**
     * Mandatory input 
     */
    private  Object inputObj;

    @Override
    protected ErrorCode executeImpl() {
        //Some business logic on inputObj
        return null;
    }

    public void setInputObj(Object inputObj) {
        this.inputObj = inputObj;
    }
} 

What is the best runtime exception to throw in case the inputObj is null ? 如果inputObj为null,抛出的最佳运行时异常是什么?

IllegalStateException seems like the best fit. IllegalStateException似乎是最合适的。 The object is not in the correct state to have executeImpl() called on it. 该对象未处于正确状态,无法对其调用executeImpl() Whatever exception you use, make sure the error message is helpful. 无论使用哪种异常,请确保错误消息都对您有所帮助。

Whether you should be using an unchecked exception at all is a whole other question... 是否还要使用未经检查的异常完全是另一个问题...

Depends on the scenario. 取决于方案。

  • If this is part of an API that another developer is using, throwing NullPointerException is reasonable since you don't want that input to be null . 如果这是另一个开发人员正在使用的API的一部分,则抛出NullPointerException是合理的,因为您不希望该输入为null Adding a descriptive exception message would be helpful. 添加描述性异常消息将很有帮助。
  • If you're not interested in throwing an NPE, or this is part of code that's not going into an API, then you could throw an IllegalArgumentException , as null could be considered an illegal argument. 如果您对抛出NPE不感兴趣,或者这是不包含在API中的代码的一部分,则可以抛出IllegalArgumentException ,因为null被视为非法参数。

If setInputObj is called with a null argument, and that's not valid, then throw NullPointerException . 如果使用null参数调用setInputObj ,并且该参数无效,则抛出NullPointerException There's some debate over the "correct" exception here ( IllegalArgumentException or NullPointerException for a null parameter? ), but Guava, Apache Commons Lang and even the JDK itself ( Objects.requireNonNull ) have settled on NPE . 关于“正确的”异常( IllegalArgumentException或NullPointerException是否为null参数? )存在一些争论,但是Guava,Apache Commons Lang甚至JDK本身( Objects.requireNonNull )都已经在NPE解决了。

If executeImpl is called before inputObj has been set, throw IllegalStateException . 如果在设置inputObj之前inputObj executeImpl ,则抛出IllegalStateException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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