Exception Handling – part 1

The Spring framework provides an annotation @ExceptionHandler that can be used to intercept uncaught/unhandled exceptions in request mapped functions in controllers.

When a user hits a url one of the request handling method of the controller class handle it and process it,but if while processing due to some reason it throws an exception such as null ponter,resourcenotfound or may be some other than it became very import to know an understand ,what user will get as response.

For our understanding ,I edited the code in StrudentRegistrationController.java so that when we hit the url it should throw Null Pointer Exception.

@RequestMapping(value=”/registrationForm.html”, method = RequestMethod.GET)
public ModelAndView getRegistationForm() throws Exception {

String exceptionOccured = “NULL_POINTER”;
throw new NullPointerException(“Null pointer Exception Occured…!”);


ModelAndView model = new ModelAndView(“RegistrationForm”);
return model;


Ofcourse this should not be shown to the user,then how to handle this,

To handle this we have to add

  1. JSP page NullPointerException.jsp
  2. Include a method with @ExceptionHandler annotation on top of it.

In our Controller class include the below method with @ExceptionHandler annotation on top of it.

@ExceptionHandler(value = NullPointerException.class)
public String handleNullPointerException(Exception e){
return “NullPointerException“;

With these changes we are done to handle NullPointerException.


Now whenever in our controller class any NullPointerException will our then user will get below page on browser instead of the entire message that we saw earlier


In this way we can handle multiple exception that are expected that may be thrown from our controller class like IOException,ArithmeticException and so on…

But what about in case if your application come accross an exception which we have not handled ,In that case the user will get the default error we have see at the start of the post.

To handle this we will provide a generic method  with @ExceptionHandler(value = Exception.class) on top of it which will handle the generic exception


We will add a generic view as Exception.jsp and user will see this page in browser.


Hope this article is help full to you,Happy Learning… 🙂


Comments are closed