Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null Pointer in catch block

I am using a try catch block to catch an exception. The console shows that it is throwing a null value. But it is not going to the catch block.

try {
        System.out.println("Exception here "+SomeObject.getValue());
    } catch (NullPointerException e) {
        // TODO: handle exception
        SomeObject so = new SomeObject();
    }
    SomeObject.setValue(); 
}

How could this be handled. Can I also use method level throws NullPointerException ?

like image 322
Some Java Guy Avatar asked Oct 23 '25 07:10

Some Java Guy


1 Answers

It indeed would have went inside the catch block. There is another potential NullPointerException at the line (assuming you are trying to say)

so.setValue(); 

Having said that it is not advised to throw RuntimeException. It is better you handle NullPointerException in your code not through try/catch but through simple condition checks

like image 189
bragboy Avatar answered Oct 25 '25 21:10

bragboy