Java:快速/优雅的方式来检查null

时间:2011-04-01 01:20:59

标签: java error-handling

在我正在编写的程序中,我发现自己正在做很多事情......

Map<String,List<String>> network = loadSerializedObj(file); // null if failed
if(network != null) {
    anonNet = util.anonymize(newNet);
} else {
    // Some sort of error handling.
    System.out.println("Some sort of error message. Exiting...");
    System.exit(0);        
}

是否有更简洁的方法来处理从文件加载序列化对象的事件不起作用且方法返回null?任何提示都是受欢迎的。在哪里,我可以让它更优雅?

7 个答案:

答案 0 :(得分:6)

你应该使loadSerializedObj抛出异常而不是返回null。当你没有任何东西可以返回时,你可以返回null。当事情发生时,你应该抛出异常。

答案 1 :(得分:2)

在这种情况下,您可以使用异常catch。

Map<String,List<String>> network = loadSerializedObj(file); // null if failed
try {
    anonNet = util.anonymize(newNet);
} catch(NullPointerException npe) {
    System.out.println("Some sort of error message. Exiting...");
    System.exit(0);        
}

但是你必须指定util.anonymize来抛出NullPointerException,如果它还没有。

答案 2 :(得分:1)

你可以有某种

class MyAssert {
  static<T> assertNotNull(T object) {
    if (object == null) {
      System.out.println("something is wrong...");
      System.exit(0);
    }
    return object;
  }
}

答案 3 :(得分:1)

尝试返回empty map而不是空值:

    if(!loadSerializedObj(file).isEmpty()) 
    {
        anonNet = util.anonymize(newNet);
    } 
    else 
    {
        // error handling    
    }

    private Map<String,List<String>> loadSerializedObj(File file) 
    {
        // do stuff
        if(mapObject == null)
        {
            mapObject = Collections.emptyMap();
        }
        return mapObject
    }

答案 4 :(得分:0)

你可以对名为n(object)的函数进行静态导入,如果为null则返回boolean。或者使用Groovy :)

答案 5 :(得分:0)

我认为你所拥有的就像保持易于阅读/维护代码一样好。

答案 6 :(得分:0)

Guava的preconditions可以是一种简洁易读的好方法。

Preconditions.checkNotNull(myReference, "My error message");