【问题标题】:NullPointerException, can I use throws because I "expect" code might crash because of NullPointerException? [duplicate]NullPointerException,我可以使用 throws 因为我“预期”代码可能会因为 NullPointerException 而崩溃吗? [复制]
【发布时间】:2017-12-14 06:10:10
【问题描述】:

当方法体中的代码可能因为 NullPointerException 而崩溃时,我可以用 throws 声明我的方法吗

我在这个方法中有 a.getB().getC() 这样的代码

编辑:

Catching nullpointerexception in Java

我已经尝试过使用示例代码,

class B {
    public void methodB() {}
}

class A {
    public void methodA(B b) throws NullPointerException {
        b.methodB();
    }
}

@Test
public void test_null_pointer() {
    boolean thrown1 = false;
    boolean thrown2 = false;
    A a = new A();

    try {
        B b = new B();
        a.methodA(b);
    } catch (NullPointerException n) {
        thrown1 = true;
    }

    try {
        a.methodA(null);
    } catch (NullPointerException n) {
        thrown2 = true;
    }

    assertFalse(thrown1);
    assertTrue(thrown2);
}

测试成功。

【问题讨论】:

标签: java exception try-catch


【解决方案1】:

你的方法会抛出异常吗?

public static boolean getC() throws Exception{
    if(Some Condition)
        throw new Exception("Some Error");
    else
        return true;
}

public static boolean getC() throws Exception{
    try{
        ... Do Something ...
        return true;
    }catch(Exception e){
        throw e
    }
}

如果是这样,您可以在方法抛出异常时捕获异常。

public static void main(String args[]){
    try{
        boolean isOK = getC(); 
    }catch(Exception e){
        System.out.println(e.getMessage());
    }
}

【讨论】:

    【解决方案2】:

    你可以使用可选的

    public YourObjectC getC(){
    YOurObjectA a = new YourObjectA();
    Optional<YourObjectC> opt = Optional.ofNullable(a)
                                        .map(YOurObjectA::getB)
                                        .map(YourObjectB::getC);
    
    return opt.orElseThrow(NullPointerException::new);
    
    }
    

    方法将返回对象 C 但如果对象为 null 将抛出 Null Pointer exc

    【讨论】:

      【解决方案3】:

      你不应该。

      如果这可能为空,您必须在这种情况下验证并应用您的业务规则。否则,我认为检查 must have 参数是否为空然后抛出IllegalArgumentException 是一个好习惯。例如,您可以在 Javadoc 上描述此行为。但是声明method throws 是没有用的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-09
        • 1970-01-01
        • 1970-01-01
        • 2020-07-05
        • 1970-01-01
        • 1970-01-01
        • 2013-11-15
        • 2019-10-11
        相关资源
        最近更新 更多