什么你要找的是try/catch/finally结构。这允许您捕获异常(错误)并对其做出反应。现在
Protected Function GetConnection() As SqlConnection
Dim ret_conn As SqlConnection
Try
ret_conn = New SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings("EUCNET00617").ToString())
ret_conn.Open()
GetConnection = ret_conn
Catch exceptionThatICaught as System.Exception
' You could also perform logging of details from exceptionThatICaught here
GetConnection = Null
End Try
End Function
,你GetConnection
函数将返回Null
当它是无法创建并打开一个连接,这意味着调用代码,它可以反应到连接返回被空,而不是崩溃。
您可能已经注意到,我把在Catch
块中的例外是System.Exception
,通常赶上这样的通用(所有异常是从System.Exception
派生)会被认为是不好的形式,因为它意味着你要照顾任何东西发生时不知道发生了什么。这只是一个例子给你看虽然=)
它总是值得检讨你包装一下你试试功能的MSDN文档页/左右赶上像他们有些人名单“预期”的(但不是所有)如果您有处理该失败案例的方法,则可能会抛出的异常可以被认为是catch
。在这种情况下,要查看的页面将是:
为SqlConnection.Open
列出两个例外,它可以抛出,InvalidOperationException
和SqlException
的文档。我强烈建议您查看该文档,以便决定“做什么”和“捕获”哪种异常类型,您认为适合您这样做。
来源
2011-02-11 13:10:40
Rob
你有没有读到“在try..catch”块?!? http://msdn.microsoft.com/en-us/library/fk6t46tz%28v=VS.90%29.aspx – BertuPG 2011-02-11 12:58:29