Java: check for null or allow exception handling

前端 未结 6 2210
旧巷少年郎
旧巷少年郎 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:32

    I agree with most of the other responses that you should prefer the null check to the try-catch. And I've upvoted some of them.

    But you should try to avoid the need as much as possible.

    There's a > 50% chance of getting nulls, because in this app. it is common to have a null if no data has been entered... so to attempt a calculation using a null is commonplace.

    That's what you should really be fixing.

    Come up with sensible default values that ensure the computation works or avoid calling a computation without supplying the needed input data.

    For many of the standard data types and computations involving them there are sensible default values. Default numbers to 0 or 1 depending on their meaning, default strings and collections to empty, and many computations just work. For more complex objects of your own making, consider the Null Object pattern.

提交回复
热议问题