我在 MSDN 网站上找到这段代码 http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open.aspx :
private static void OpenSqlConnection(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
}
}
我的问题是...该站点还指出 .Open()
可以抛出 InvalidOperationExceptions 和 SqlExceptions,但这个示例看起来并没有处理它们。
这仅仅是因为他们对代码很简短,还是因为他们不值得在这里处理?它们可能以某种方式由 using 结构处理吗?
最佳答案
Is this just because they were being brief with the code, or is there a reason they're not worth handling here? are they possibly handld by the using construct in some way?
using
关键字是 try/finally
的语法糖,即使您引用的代码不会处理可能的异常,SQL 连接也会被正确处理.他们可能没有明确地处理可能的异常,因为许多人更喜欢让异常冒泡到最高层并在那里处理异常。
关于c# - C# 中的 SqlConnection - 安全编程实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10385235/