zoukankan      html  css  js  c++  java
  • 如何优雅的使用Objects.requireNonNull(T obj, String message)定制你的NPE异常

    IDEA中习惯跟踪源码实现逻辑,多次碰到Objects.requireNonNull(T obj)这个方法,改方法主要用于提早判断对象是否为空,以便更早的抛出NPE

    平时小组开发中强调程序健壮性,不允许组员的代码中出现明显的NPE,这样多数时候都要写判空逻辑,抛出自定义的异常

    我们看下具体的源码:

    /**
    * Checks that the specified object reference is not {@code null}.
    * This method is designed primarily for doing parameter validation in methods
    * and constructors, as demonstrated below:
    * <blockquote><pre>
    * public Foo(Bar bar) {
    * this.bar = Objects.requireNonNull(bar);
    * }
    * </pre></blockquote>
    *
    * @param obj the object reference to check for nullity
    * @param <T> the type of the reference
    * @return {@code obj} if not {@code null}
    * @throws NullPointerException if {@code obj} is {@code null}
    */
    public static <T> T requireNonNull(T obj) {
    if (obj == null)
    throw new NullPointerException();
    return obj;
    }
    解释:检查定义的对象引用不为空。设计该方法主要用来做方法和构造函数中的参数校验
    如上,如果直接使用仍然是抛出一个NPE,除了能提早检测和抛出异常,无法直接在业务中使用

    继续往下滚动,发现还有这个方法
    /**
    * Checks that the specified object reference is not {@code null} and
    * throws a customized {@link NullPointerException} if it is. This method
    * is designed primarily for doing parameter validation in methods and
    * constructors with multiple parameters, as demonstrated below:
    * <blockquote><pre>
    * public Foo(Bar bar, Baz baz) {
    * this.bar = Objects.requireNonNull(bar, "bar must not be null");
    * this.baz = Objects.requireNonNull(baz, "baz must not be null");
    * }
    * </pre></blockquote>
    *
    * @param obj the object reference to check for nullity
    * @param message detail message to be used in the event that a {@code
    * NullPointerException} is thrown
    * @param <T> the type of the reference
    * @return {@code obj} if not {@code null}
    * @throws NullPointerException if {@code obj} is {@code null}
    */
    public static <T> T requireNonNull(T obj, String message) {
    if (obj == null)
    throw new NullPointerException(message);
    return obj;
    }

    and throws a customized {@link NullPointerException} if it is:定制的空指针异常

    and constructors with multiple parameters :多参数的构造函数

    这样,下次我们想抛出一个自定义的空指针异常的时候,以前是:
    if(obj==null){
      throw new xxxException("该记录不存在xxxx");
    }
    现在可以更优雅的写Objects.requireNonNull(T obj,"该记录不存在xxxx")

    代码实现区别不大,那么为啥不选择优雅^_^
     
  • 相关阅读:
    Python Scrapy框架
    Python Mongo数据库
    Python Selenium框架
    Python BeautifulSoup库使用
    Python 存入三大文件
    Python Xpath的解析,应用
    Python Requests 高级
    错误码:2003 不能连接到 MySQL 服务器在 (10061)
    MySQL连接本地数据库时报1045错误的解决方法
    iWebShop安装教程
  • 原文地址:https://www.cnblogs.com/yb38156/p/11567492.html
Copyright © 2011-2022 走看看