try/catch vs null check in java

前端 未结 10 2201
心在旅途
心在旅途 2020-12-01 14:05

Sometimes I face I must write a piece of code like this (usually it have more nested if and more complex structure but for the example is enought)

public voi         


        
10条回答
  •  既然无缘
    2020-12-01 14:23

    public void printIt(Object1 a){
        if(a==null){
            throw new IllegalArgumentException("a was null, but this is not allowed here."),
        }
        [...]
    

    Fail fast and fail hard. If a shoud not be null, throw an Exception. This will make your code more stable and reliable.

    So if I would have to decide between your a) and your b), I would choose a). But if a mustn't be null there, you would hide an error-situation.

提交回复
热议问题