try/catch vs null check in java

前端 未结 10 2211
心在旅途
心在旅途 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:27

    The answer is use version A.

    It is generally considered "bad design" to use Exceptions for flow control. Exceptions are for the "exceptional", especially NPEs which are totally avoidable using null checks. Further, using null checks, you can tell (ie log) which term is null (you won't know where the null is with your version B).

    Note that performance is not an issue any more throwing exceptions (the stack trace for example is only built if you use it). It's a matter of clean code.

    However, there are some case where using exceptions for flow control is unavoidable, for example the exceptions thrown from SimpleDateFormat.parse(), because there isn't a reasonable way to tell before making the call that your input is not parsable.

提交回复
热议问题