Why explicitly throw a NullPointerException rather than letting it happen naturally?

后端 未结 9 1459
无人共我
无人共我 2020-12-12 13:40

When reading JDK source code, I find it common that the author will check the parameters if they are null and then throw new NullPointerException() manually. Why do they do

9条回答
  •  一向
    一向 (楼主)
    2020-12-12 14:00

    It's because it's possible for it not to happen naturally. Let's see piece of code like this:

    bool isUserAMoron(User user) {
        Connection c = UnstableDatabase.getConnection();
        if (user.name == "Moron") { 
          // In this case we don't need to connect to DB
          return true;
        } else {
          return c.makeMoronishCheck(user.id);
        }
    }
    

    (of course there is numerous problems in this sample about code quality. Sorry to lazy to imagine perfect sample)

    Situation when c will not be actually used and NullPointerException will not be thrown even if c == null is possible.

    In more complicated situations it's becomes very non-easy to hunt down such cases. This is why general check like if (c == null) throw new NullPointerException() is better.

提交回复
热议问题