1

...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.

2 Answers2

0

None of these, just inherit from RuntimeException or another exception that inherits from RuntimeException as IllegalArgumentException.

Maurício Linhares
  • 39,901
  • 14
  • 121
  • 158
0

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.

Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
  • In my example with the Login class, isn't this whole step an IO due to the user inputting credentials? Or IOException is not made for that? –  Nov 24 '12 at 06:05
  • @Andrysse: If your `Login` class is reading the user's input directly from the input device, then there could be an IOException but in server based applications, that is not the case. **You capture the user input in the client side and then pass the input as parameter to the server component**. In that case, it will not be an `IOException`. – Yogendra Singh Nov 24 '12 at 06:09