【发布时间】: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);
}
测试成功。
【问题讨论】:
-
你试过了吗?
-
我能回答一下吗
-
不建议抓,不过可以看这个stackoverflow.com/a/15146645/5156075