我知道如何在数据库调用的情况下使用try / catch块,并且知道如何在使用try / finally构造的上下文中使用“using”指令。
但是,我可以混合它们吗?我的意思是当我使用“using”指令时,我可以使用try / catch构造,因为我仍然需要处理可能的错误吗?
答案 0 :(得分:2)
你绝对可以同时使用它们。
using
块基本上只是一个try / finally块的语法糖,如果你愿意,你可以嵌套try / finally块。
using (var foo = ...)
{
// ...
}
大致相当于:
var foo = ...;
try
{
// ...
}
finally
{
foo.Dispose();
}
答案 1 :(得分:1)
当然你可以这样做:
using (var con = new SomeConnection()) {
try {
// do some stuff
}
catch (SomeException ex) {
// error handling
}
}
using
由编译器翻译为try..finally
,因此与在try..catch
内嵌套try..finally
没有什么不同。
答案 2 :(得分:0)
这个完全有效:
using (var stream = new MemoryStream())
{
try
{
// Do something with the memory stream
}
catch(Exception ex)
{
// Do something to handle the exception
}
}
编译器会将其转换为
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();
}
}
当然,这种嵌套也是相反的(就像在using
块中嵌套try...catch
- 块一样。
答案 3 :(得分:0)
using
,例如:
using (var connection = new SqlConnection())
{
connection.Open
// do some stuff with the connection
}
只是编码以下内容的语法快捷方式。
SqlConnection connection = null;
try
{
connection = new SqlConnection();
connection.Open
// do some stuff with the connection
}
finally
{
if (connection != null)
{
connection.Dispose()
}
}
这意味着,是的,你可以将它与其他try..catch或其他任何东西混合使用。这就像在try..catch
中嵌套try..finally
一样。
它只是作为一种快捷方式,确保您“使用”的项目在超出范围时被处理掉。它对您在范围内的操作没有任何实际限制,包括提供您自己的try..catch
异常处理。