Java: check for null or allow exception handling

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

    Try and catch are close to "free" but throws can be very expensive. Typically VM creators do not optimize exception paths since, well, they are exceptional (supposed to be rare).

    NullPointerException indicates a programmer mistake (RuntimeException) and should not be caught. Instead of catching the NullPointerException you should fix your code to cause the exception not to be thrown in the first place.

    Worse yet, if you catch the NullPointerException and a different part of the calculation code throws NullPointerException than the one you expect to throw it you have now masked a bug.

    To fully answer your question, I would implement it one way, profile it, and then implement it the other way and profile it... then I would only use the one with the if statement that avoids throwing the NullPointerException regardless of which is faster simply because of the point above.

提交回复
热议问题