Can I declare my method with throws when code in method body might crash because of NullPointerException
I have code like a.getB().getC()
inside this method
Edit:
Catching nullpointerexception in Java
I have tried with sample code,
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);
}
Test has succeeded.