Snake Snake - 1 month ago 6
Java Question

How to identify a throwable with specific data

I have this caught that catches any uncaught exception

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
}
});


Inside the method, I want to deal with following exception differently than other exceptions:

Caused by: java.lang.NullPointerException
at com.company.si.stats.Statistics.hashString(Statistics.java:192)
at com.company.si.stats.Statistics.sendStatistics(Statistics.java:127)


I want basically to check that it is nullpointer exception coming from
com.company.si.stats.Statistics.hashString


How can I do that? I am not sure what parameters in throwable I should compare against?

The code where exception is thrown was not written by me, so I cannot change anything about it.

Answer

Disclaimer

This was suggested in the comments and I thought it will be a good idea to add it as an answer, but remember that this is not how you should do it, so please use this answer as an example of NOT to handle this type of problem. Feel free to also downvote it.


You can check where the exception comes from by looking at its stack trace, or at least at first stack trace element.

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
   @Override
   public void uncaughtException(Thread t, Throwable e) {
       StackTraceElement[] stackTrace = e.getStackTrace();
       if (e instanceof NullPointerException &&
           stackTrace != null && stackTrace.length >= 0 &&
           "Statistics.java".equals(stackTrace[0].getFileName()) &&
           "hashString".equals(stackTrace[0].getMethodName()) &&
           192 == stackTrace[0].getLineNumber()) {
           // Handle your exception here.
       }
   }
});

Reasons why you shouldn't do it:

  1. it's really ugly
  2. any change in hashString method will make this useless
  3. because mom said so
  4. any change in Statistics class will make this useless
  5. in case of 2 or 4, finding bugs caused by this exception could be really painful
  6. it's not portable (think about changing the library in the future)
  7. it's bad practice