-3

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.

Bhargav
  • 85
  • 1
  • 9

3 Answers3

1

Do your method throw the exception?

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

or

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

If it do, you can catch the exception when the method throw the exception back.

public static void main(String args[]){
    try{
        boolean isOK = getC(); 
    }catch(Exception e){
        System.out.println(e.getMessage());
    }
}
鄭有維
  • 265
  • 1
  • 13
1

You can use Optional

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

return opt.orElseThrow(NullPointerException::new);

}

Method will return object C but if object is null will throw Null Pointer exc

Almas Abdrazak
  • 3,209
  • 5
  • 36
  • 80
0

You should not.

If this may be null, you must verify and apply your business rules in this case. Otherwise, I think is a good practice you to check if a must have parameter is null and then you throw an IllegalArgumentException. You can describe this behavior on your Javadoc, for instance. But to declare a method throws is useless.

Fabiano
  • 1,344
  • 9
  • 24