4

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 ?

Some Java Guy
  • 4,992
  • 19
  • 71
  • 108
  • 2
    Please post the stack trace and identify the line from which the exception is thrown. – Ted Hopp Dec 23 '11 at 06:48
  • 1
    strange!! why to handle null pointer exception while null values should be handled by cheeking values for any null values – Umesh Awasthi Dec 23 '11 at 06:50
  • What do you mean that the console shows it is throwing a null value? Your println is not in the catch block. – user949300 Dec 23 '11 at 06:50
  • Use exceptions in really exception cases. Provided code shows incorrect exception usage. Why not just check that `SomeObject` is null? – Slava Semushin Dec 23 '11 at 06:54

3 Answers3

3

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

bragboy
  • 34,892
  • 30
  • 114
  • 171
  • From the statement `SomeObject so = new SomeObject()`, it appears that `SomeObject` is a class name. This would suggest that `setValue()` is a static (class) function. If there was a NPE thrown, it would be from inside that function, not from this statement. – Ted Hopp Dec 23 '11 at 06:51
  • @TedHopp : Agreed. Corrected answer – bragboy Dec 23 '11 at 06:51
0

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());
Rajesh Pantula
  • 10,061
  • 9
  • 43
  • 52
0

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) {
}
Avil
  • 453
  • 3
  • 15