try/catch vs null check in java

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

    A code should never include exception handlers for unchecked exceptions. A null check should always be used for an object reference which has a chance of being null.

    0 讨论(0)
  • 2020-12-01 14:34

    If you migrate to Java 8 you can use Optional and Lambdas. First, you need to rewrite your classes to return Optional of each type:

    class Object1 {
        private SubObject b;
    
        Optional<SubObject> getB() {
            return Optional.ofNullable(b);
        }
    }
    
    class SubObject {
        private SubObject2 c;
    
        Optional<SubObject2> getC() {
            return Optional.ofNullable(c);
        }
    }
    
    class SubObject2 {
        @Override
        public String toString() {
            return "to be printed";
        }
    }
    

    Now, you can chain the calls without the risk of NullPointerExceptions in a concise way:

    a.getB()
        .flatMap(SubObject::getC)
        .ifPresent(System.out::println);
    

    See the Oracle's article Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional! for more information.

    0 讨论(0)
  • 2020-12-01 14:38

    The wrongest part of the second version is that when a NPE happens inside the getB(), getC() it will be silently ignored. As already mentioned, exceptions are for exceptional cases.

    0 讨论(0)
  • 2020-12-01 14:46

    Using Java 8 optional:

    Optional.ofNullable(a)
                .map(Object1::getB)
                .map(SubObject::getC)
                .ifPresent(Object2::print);
    
    0 讨论(0)
提交回复
热议问题