Spring 3.0 MVC ExceptionHandler

I am 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 second:

 @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 am writing my code to throw this exception:

The first line throws an arithmetic exception:

 System.out.println(100/0); 

Throws the correct exception, and exception.getMessage () returns a "/ zero" message.

now I am trying to throw the second exception:

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

Excluded, but exception.getMessage () returns null and the stack. Tracing is also zero.

Interestingly, in log4j logger, I see a full stack trace for both exceptions. Why does he behave this way?

+4
source share
2 answers

Like affe said, null is a message. You attach the message only to the model that will be displayed, so you will not see the stack trace.

My advice is that planning a null pointer is not worth it. NPE is a programmer error, which, if presented to the user, is a defect or error.

Also, based on your code, you handle and present all exceptions the same way, so you might have an exception handler that just handles a Throwable or Exception . This can also be done through configuration or even in your web.xml .

+3
source

"null" is the message you receive from the NullPointer exception. This is just java. You did not send any codes that tried to manipulate the stack trace, or anything using log4j, so you cannot say why this might have inconsistent results.

+1
source

All Articles