Home  >  Q&A  >  body text

异常 - 如何更好地处理 java NullPointerException (一整套完整心法) ?

2017/1/8

描述

可以说是「优雅地」处理, 总的来说要逻辑严谨, 即讲清楚 why

自己脑海有某些原则, 但是总不是不系统, 这令我不安.

上下文环境

  1. Java 8

伊谢尔伦伊谢尔伦2711 days ago420

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-04-18 10:36:35

    Just to mention a few that are more commonly used or more official:

    java8 provides the optional class for null pointer checking,
    Guava provides Preconditions.checkNotNull for checking,
    lombok provides the NonNull annotation

    However, in actual use, if(map!=null&&map.get("a")!=null) is relatively simple and intuitive, and lombok is very elegant to use.
    As for the handling methods of java8 and guava, it is a matter of opinion.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:36:35

    The meaning of optional is to tell you through the type system that you should perform null checking, but you don’t need to check for variables that are not optional? No, you still have to check. Therefore, the use of optional is awkward, and unless it is new code, it is difficult to handle it consistently.

    optional refers to option/maybe in functional languages, but there is usually no null in functional languages. If you see an option, you will detect it. If there is no option, you don’t need to check. The processing is consistent.

    Recent TypeScript supports strictNullCheck and union type. Null becomes a separate type. Combined with union type, it can represent nullable types at the type level (such as string | null). strictNullCheck requires that all nullable variables must be checked before use.

    You can annotate and mark NonNull in Java, and then use tools to detect it, and the effect is almost the same.

    reply
    0
  • Cancelreply