1

I am having my first foray into Java servlet programming, and since I am more seasoned with "server side" programming, I have taken a few habits of dealing with Writers and OutputStreams. However, maybe these habits are not suitable when programming servlets, and the available Javadoc does not clearly answer the two questions I have below.

First question: should you catch IOExceptions thrown when you attempt to write to them? Provided that you don't, what is the default behaviour of servlet containers in this case (ie, what is the HTTP return code)?

Second question: should you let the servlet engine close the OUtputStream/Writer for you? Is there any danger in closing it yourself inside the servlet?

fge
  • 119,121
  • 33
  • 254
  • 329

1 Answers1

2

First question: should you catch IOExceptions thrown when you attempt to write to them? Provided that you don't, what is the default behaviour of servlet containers in this case (ie, what is the HTTP return code)?

The default error code for random exceptions thrown from a servlet is generally 503 (internal server error), but i don't think there's a requirement for that (i.e. different servlet containers may do different things). whether or not you should catch the exception and handle it yourself is entirely up to what behavior your servlet needs to have (maybe you have different error codes for different situations, maybe you want to proceed even if you can't read all the data, etc.).

Second question: should you let the servlet engine close the OUtputStream/Writer for you? Is there any danger in closing it yourself inside the servlet?

I believe most(all?) servlet engines will close the stream for you, however i would still say it's a best practice to close it yourself.

jtahlborn
  • 52,909
  • 5
  • 76
  • 118