问题描述
我知道使用语句处理掉正在创建的对象.就像我想做这样的事情:
I know that Using statement disposes out the object that is being created. Like if I wanted to do something like this:
Using(SqlConnection conn = new SqlConnection(connString))
{
//some code
//How to show the users if conn is not opened up or generated some kind of error?
}
如果 conn 未打开或产生某种错误,如何向用户显示?
How to show the users if conn is not opened up or generated some kind of error?
推荐答案
写在 using
块中的代码没有什么特别之处 - 只需使用 try.catch
来处理例外:
There's nothing special about code written inside a using
block - just use a try.catch
to handle exceptions:
using(SqlConnection conn = new SqlConnection(connString))
{
try
{
conn.Open();
// do more stuff here......
}
catch(SqlException sqlEx)
{
// log error and possibly show to user in a MessageBox or something else
}
}
using(...) { ... }
块本身仅被设计来确保它封装"的资源/对象在不再需要它了.using
语句本身无法处理错误.
The using(...) { ... }
block itself is designed only to ensure that the resource / object it "encapsulates" is properly disposed of when it's no longer needed. There's is nothing you can do with the using
statement itself to make it handle errors.
因此,如果您预计仅创建对象可能会失败,那么您必须将整个 using
块放在 try ... catch
块中,或者回到 try ... catch ... finally
块并确保自己正确处理(正如 Adam 在他的回答中所建议的那样).
So if you expect that just creating the object could fail, then you'd have to put the entire using
block inside the try ... catch
block , or fall back to a try ... catch ... finally
block and ensure proper disposal yourself (as Adam suggested in his answer).
这篇关于在 Using 语句中捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!