A short answer is that you don't have to dispose it although it is a good exercise to dispose any IDisposable
objects that you own.
In fact, trying to dispose WebException.Response
or the stream returned from it would cause problems you mentioned since you may encounter code attempting to read its properties in upper call chain's exception handler.
The reason why it is safe not to dispose it is because HttpWebRequest
internally makes a memory stream from the network stream before it throws WebException
, and the underlying network stream has already been closed/disposed. So it doesn't really have any unmanaged resource associated at that point. This I assume was a decision to make it easier to handle the exception.
Unfortunately MSDN documentation doesn't have any explanation about this behavior. Technically the implementation can change in future causing problem to your code not disposing the HttpWebResponse
and/or associated stream you get from WebException
, but it is highly unlikely that this behavior would change the implementation given many applications depend on current behavior.
I have to add though that it is a good practice that you should dispose IDisposable
objects you own. If possible, use HttpClient
class instead so that you don't have to deal with this situation at all. If you can't, consider handling the WebException
yourself and throw new type of exception that does not expose WebException
to the caller of your code so that you don't run into a situation where a caller is trying to access WebException.Response
after you dispose it.
Disclaimer: I work for Microsoft, but this does not represent my employer or .NET Framework team's view. No warranty implied.