Java: check for null or allow exception handling

前端 未结 6 2170
旧巷少年郎
旧巷少年郎 2020-12-10 04:56

I\'m wondering about the cost of using a try/exception to handle nulls compared to using an if statement to check for nulls first.

To provide more information. There

6条回答
  •  一生所求
    2020-12-10 05:18

    If passing null argument is an exceptional case, then I'd throw a NullPointerException.

    public Result calculate(Input input) {
        if (input == null) throw new NullPointerException("input");
        // ...
    }
    

    If passing null is an allowed case, then I'd skip the calculation and eventually return null. But that makes in my opinion less sense. Passing null in first instance would seem a bug in the calling code.

    Whatever way you choose, it should be properly documented in the Javadoc to avoid surprises for the API user.

提交回复
热议问题