Try Catch Finally and variable declaration
-
I have the following simple code, yet in the finally block the compilier says that "'con' is not declared." What's up with this? (LogEvent is just an event log wrapper function which works like a champ.)
Try Dim con As New SqlConnection(Configuration.Settings("ConnectionString")) Dim cmd As New SqlCommand("INSERT INTO Messages (MessageType, Message) VALUES('" & _ MessageType & "','" & Message & "')", con) cmd.ExecuteNonQuery() Catch e As Exception LogEvent(e.ToString(), EventLogEntryType.Error) Finally con.Close() '<- compiler error here: "con" is not declared. End Try
-John -
I have the following simple code, yet in the finally block the compilier says that "'con' is not declared." What's up with this? (LogEvent is just an event log wrapper function which works like a champ.)
Try Dim con As New SqlConnection(Configuration.Settings("ConnectionString")) Dim cmd As New SqlCommand("INSERT INTO Messages (MessageType, Message) VALUES('" & _ MessageType & "','" & Message & "')", con) cmd.ExecuteNonQuery() Catch e As Exception LogEvent(e.ToString(), EventLogEntryType.Error) Finally con.Close() '<- compiler error here: "con" is not declared. End Try
-Johncon needs to have been declared outside of the try block, as thus:
Dim con As SqlConnection Dim cmd As SqlCommand Try con = New SqlConnection(Configuration.Settings("ConnectionString")) cmd = New SqlCommand("INSERT INTO Messages (MessageType, Message) VALUES('" & _ MessageType & "','" & Message & "')", con) cmd.ExecuteNonQuery() Catch e As Exception LogEvent(e.ToString(), EventLogEntryType.Error) Finally con.Close() End Try
-John