-2

Is there is any tool to capture all the null pointer exception in the java project? Am working in the mobile application testing, during my testing I have noticed so many null pointer exceptions which are not captured properly during the implementation.

Anyone suggest me the best tool in the online to capture the null pointer exception

  • What do you mean by "to capture"? Exception is an event. Do you want to capture it in runtime (aka catch/handle) or you want to know where they could arise in your code? The latter is hardly possible, otherwise devs would use that tool. Some hints on the possible places where the exception might occur can be provided by your IDE. – Alexey R. Mar 29 at 10:24
  • @AlexeyR. Actually, am looking a tool to list out all the null pointer exception like Sonarcube can show some syntax error in the code like that any other tool is there to check all the null pointer exception in the code – Anand Mar 29 at 13:08
  • I'm afraid there is no such the tool. Exceptions are runtime mechanism. So whether they will appear or not depends on the code runtime logic that might base on a lot of conditions (for example the method could return null if it cannot locate a file and you assign the method output to the object reference). Or even more the logic itself might be built in runtime using reflection. – Alexey R. Mar 29 at 15:53
  • @Anand - To me, the best tool for catching an NPE is a try/catch block. – Brian Mar 29 at 17:10
  • @Anand, if you find some answer acceptable, please, mark it as "Accepted". – João Farias Mar 31 at 11:19
3

The cleanest way is to create an aspect before the Exception is thrown and deal with it:

public aspect ExceptionLoggingAspect {

    before (NullPointerException e): handler(Exception+) && args(e) {
        System.err.println("Caught by aspect: " + e.toString());
        e.printStackTrace();
    }
}

More details here.

The alternative is not change the code every time you see a NPE...

(You don't want to do this...)

1

You can run your Java application in debug mode in your favourite IDE and listen for NullPointerExceptions.

For instance, in Intellij that would be: Run | View Breakpoints | Exception Breakpoints. You can find more here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.