javaexceptionservletsioexceptionservletexception

ServletException or IOException?


...I never can decide between these two. I'm always going back to the code and switching between.

When you're coding - let's say a Login class - from an (extended) HttpServlet, which sports both ServletException and IOException, and you just want to throw further your exception (e.g. NoSuchAlgorithmException, NamingException) to see it in a page of your application later, which one do you throw it through: ServletException or IOException?

P.S.: I don't try to catch every possible NoSuchAlgorithmException, NamingException, etc. because I can miss a real cause that I haven't seen before and treat it the wrong way or inform the wrong thing to the user.


Solution

  • IOException has its own meaning. An IOException should be only thrown when there as an issue in IO operations e.g. reading/writing data from file or URL. If I have to make choice between the two, I will choose ServletExcetion.

    But if there is a room to define better exception handling then I would like to create my own custom exception class e.g. MySystemException extending RuntimeException and wrap the relevant exceptions as MySystemException and throw it.