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 ?

有帮助吗?

解决方案

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

其他提示

it is a bad idea to catch UnChecked Exceptions, rather than catching NullPointerExcetpion, you can simple check for null values in an If condition.

if(SomeObject.getValue()!=null)
System.out.println(SomeObject.getValue());

You can put another try block inside catch

try {
    doSomething();
} catch (IOException) {
         try {
                  doSomething();
         } catch (IOException e) {
                 throw new ApplicationException("Failed twice at doSomething" +
                 e.toString());
         }          
} catch (Exception e) {
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top