问题
I know how to use try/catch block in case of database calls and know how to use "using" directive in context of using try/finally construction as well.
But, can I mix them? I mean when I use "using" directive can I use try/catch construction as well because I still need to handle possible errors?
回答1:
Of course you can do it:
using (var con = new SomeConnection()) {
try {
// do some stuff
}
catch (SomeException ex) {
// error handling
}
}
using
is translated by the compiler into a try..finally
, so it's not very different from nesting a try..catch
inside a try..finally
.
回答2:
You can definitely use both together.
A using
block is basically just a bit of syntactic sugar for a try/finally block and you can nest try/finally blocks if you wish.
using (var foo = ...)
{
// ...
}
Is roughly equivalent to this:
var foo = ...;
try
{
// ...
}
finally
{
foo.Dispose();
}
回答3:
This one is perfectly valid:
using (var stream = new MemoryStream())
{
try
{
// Do something with the memory stream
}
catch(Exception ex)
{
// Do something to handle the exception
}
}
The compiler would translate this into
var stream = new MemoryStream();
try
{
try
{
// Do something with the memory stream
}
catch(Exception ex)
{
// Do something to handle the exception
}
}
finally
{
if (stream != null)
{
stream.Dispose();
}
}
Of course this nesting works the other way round as well (as in nesting a using
-block within a try...catch
-block.
回答4:
A using
such as:
using (var connection = new SqlConnection())
{
connection.Open
// do some stuff with the connection
}
is just a syntactic shortcut for coding something like the following.
SqlConnection connection = null;
try
{
connection = new SqlConnection();
connection.Open
// do some stuff with the connection
}
finally
{
if (connection != null)
{
connection.Dispose()
}
}
This means, yes, you can mix it with other try..catch, or whatever. It would just be like nesting a try..catch
in a try..finally
.
It is only there as a shortcut to make sure the item you are "using" is disposed of when it goes out of scope. It places no real limitation on what you do inside the scope, including providing your own try..catch
exception handling.
来源:https://stackoverflow.com/questions/13082590/c-using-directive-and-try-catch-block