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开发者_如何学C");
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?
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.
"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.
精彩评论