On the basis of what is written on this web page, and if I understand correctly, the using
statement works like a try/finally
, so I might mistakenly expect that if an exception occurs in a using
statement, it should not crash the program.
However, when the DownloadString
method, shown in the example below, throws a WebException
, the program crashes.
using (WebClient client = new WebClient())
{
string response = client.DownloadString(url);
// ...
}
This is normal, since the using
statement does not work like a try/catch/finally
, then actually no exception is handled. But then I wonder what is the purpose of the using
statement.
UPDATE... Based on responses below, I add the following considerations. Basically, if I need to handle an exception, possible solutions could be as follows.
using
statement inside a try/catch
block.DonwloadString
method inside a try/catch
block.Sample code for the third solution.
WebClient client = new WebClient();
try
{
string response = client.DownloadString(url);
// ...
}
catch(Exception ex)
{
// handle (or ignore) the exception
}
finally
{
if (client != null)
client.Dispose();
}
if I understand correctly, the using statement works like a try/finally
Correct.
so I would expect that if an exception occurs in a using statement, it should not crash the program.
Incorrect.
Neither try/finally
nor using
statements swallow exceptions - if you don't catch the exception, it will propagate up. If it's uncaught, it will usually terminate the process. (There are a few cases where it won't, based on which thread it's in and how the CLR is configured, but that's a different matter.)
But then I wonder what is the purpose of the using statement.
To make it simpler to write code that needs to dispose of resources. That's all. If we didn't have using
statements, we'd have a lot of try
/finally
blocks which just called Dispose
... and that would be considerably uglier. (Been there, done that - that was Java until Java 7 introduced the try-with-resources statement.)
See more on this question at Stackoverflow