views:

47

answers:

2

I'm writing my Exception Handler from Spring MVC controller and I have the following code:

@ExceptionHandler(NullPointerException.class)
      public ModelAndView handleMyException(NullPointerException  exception) {
    System.out.println(exception.getMessage());
        ModelAndView modelAndView = new ModelAndView("/errors/404");
        modelAndView.addObject("message", exception.getMessage());
           return modelAndView;
      } 

and the second one:

@ExceptionHandler(ArithmeticException.class)
  public ModelAndView handleException(ArithmeticException exception) {
System.out.println(exception.getMessage());
    ModelAndView modelAndView = new ModelAndView("/errors/404");
    modelAndView.addObject("message", exception.getMessage());
       return modelAndView;
  }

Now I'm writing my code in order to throw those exception:

The first line throws Arithmetic exception:

System.out.println(100/0);

It throws correct exception and and exception.getMessage() returns message "/ by zero".

now I'm trying to throw second exception by:

String test = null;
System.out.println(test.charAt(2));

The exception is raised, however exception.getMessage() return null and stack Trace is null as well.

The interesting thing is that in log4j logger I see full stack trace for both exceptions. Why does it behave that way?

A: 

"null" is the message you get on a NullPointer exception. That's just java. You didn't post any code that's attempting to manipulate the stack trace, or anything using log4j, so can't really say why that might have inconsistent results.

Affe
Yes. There is null in stacktrace and in the message. I know that this is ugly to show NPE to the user, but my goal is to understand how the system work and why do i have inconsistant behavior.
danny.lesnik
I was saying, you didn't post any of the code that's resulting in inconsistent behavior, so how are we supposed to help you with it?
Affe
+2  A: 

Like affe said, null is the message. You're only attaching the message to the model to be displayed, so you won't see the stack trace.

My advice is that planning for a null pointer isn't worthwhile. A NPE is a programmer error that, if presented to the user, is a defect or bug.

Also, based on your code, you treat and present all exceptions identically, so you could have an exception handler that simply handles Throwable or Exception. This can also be done via the config, or even in your web.xml.

hisdrewness