tags:

views:

153

answers:

1

I have been throwing ServletExceptions in the past, when something/anything goes wrong in a Servlet, mostly just wrapping the exception in the ServletException.

Now I am thinking it is actually better to not throw a ServletException, but to respond with response.sendError(sc) and use the correct HTTP status codes.

if I can't send an error using reponse.sendError, (IOException), I wrap the IOException in a ServletException.

Is the above a better way to respond? When is it OK to just throw a ServletException?

+1  A: 

It is better to throw a ServletException.

You can later actually catch this exception with error-page directive in your web.xml, and make appropriate actions: display a fancy error page to user, send the exception along with the stack trace to developers, write it to logs and so on.

If you just use sendError(), you can't do that, to various extents.

alamar
I actually forgot about that, in the past I did do the same thing in web sites. At the moment I am using a servlet to create a simple XML web service, so in that context there is no page to show. Thanks for the reminder!
Raymond Roestenburg