Exception handling in RESTful web services (JAX-RS) is a very important concept, in this article we are going to explain it step by step with an example. check this article for Creating Simple Maven RESTful Web Service Project in Eclipse.

As we are dealing with exception handling here, we are going to create a service which will throw an exception.








In this Example we have created 4 java classes to understand Exception Handling in Web Services.

  • RESTResource.java
  • RESTService.java
  • CallDB.java
  • MyData.java

The application will start by hitting the following URL

  • If you hit the above URL, the flow will come to RESTResource.java, in that at line number 15, we are calling checkCustomerStatus() function of RESTService class, by passing the id.
  • Consider, CallDB is a class which handle all database related stuff, so in RESTService.java at line number 11, we are calling getStatus() of CallDB.
  • In CallDB.java consider we had a database call at line number 7, after that creating MyData class object and setting all the data that We have retrieved from the database and returning it at line number 13, if you observe line number 11, We have commented the setter method, means We are not setting status, so by default it contains NULL value. ( if we call its getter method, it will return NULL)
  • Now the flow will come to RESTService.java at line number 11, We are calling getStatus(), as this gives null value [as we have not set anything in CallDB at line 11], on that null We are calling .trim() again, which will give NullPointerException.

So successfully we are able to create a service, which will throw a NullPointerException. If you hit the URL, you will see.

Custom (user defined) run time exception

Now,We are going to create a custom (user defined) run time exception, lets say my custom exception class name is CustomerDataNotFoundException.

Here We have just created an exception class with constructor which takes String as an argument.


Now let me change RESTService.java as:


We are checking the status with if condition. If status is NULL, throwing out the custom exception by passing some meaningful message. Lets run the application and see.

Its throwing our exception with the message we have sent.That’s all for Exception Handling in Web Services, Hope you liked it. Keep Learning and Sharing 🙂 !!

Leave a Reply

Your email address will not be published. Required fields are marked *