Try, Catch
Quick Example…
Dim a As String = "Hello World"
Dim b As Integer
Try
b = CInt(a)
Catch ex As Exception
MsgBox(ex.ToString())
End Try
The above code will cause an “Exception” when it “Try”'s to make a an integer. (b = CInt(a))
It will be handled by the Try and Catch blocks in the code..
All you will recive is a MsgBox with the error discription, and the rest of the code will continue to run.
Different Exceptions
When you are making programs your not just dealing with regular Exceptions. There will be SqlException’s, InvalidCastException’s, and FileNotFoundException’s, among others… lots of others…
In our previous example we were really catching a InvalidCastException, because it is Invalid to make a string “Hello World” into an Integer.
We would then do the following..
Dim a As String = "Hello World"
Dim b As Integer
Try
b = CInt(a)
Catch ex As InvalidCastException
MsgBox("I'm Sorry, but you can't do that..." & vbcrlf & vbcrlf & ex.Message)
End Try
System.Exception Main Members
If you noticed… in the last example I used ex.Message instead of ex.ToString()… the folowing are the main members or the System.Exception class and are used by all Exception’s in the .NET Framework
ex.HelpLink
'(String) Gets or sets a link to the help file associated with this exception.
ex.InnerException
'(System.Exception) Gets the System.Exception instance that caused the current exception.
ex.Message
'(String) Gets a message that describes the current exception.
ex.Source
'(String) Gets or sets the name of the application or object that causes the error.
ex.StackTrace
'(String) Gets a string representation of the frames on the call stack at the time the current exception was thrown.
ex.ToString
'(String) Creates and returns a string representation of the current exception.
Using Finally
You can also add Finally to your Try and Catch block to run code no matter what happens.
Dim a As String = "Hello World"
Dim b As Integer
Dim MyMessage As String
Try
b = CInt(a)
MyMessage = "Sucessfully made the string 'a' to an integer in 'b'."
Catch ex As InvalidCastException
MyMessage = "Could not make the string 'a' into an integer 'b'."
Finally
MsgBox(MyMessage)
End Try
Ok… now lets look at that…
I added Dim MyMessage As String, to hold our message.
Then in the Try section of our block I added MyMessage = “Sucessfully made the string ‘a’ to an integer in ‘b’.”, This line will ONLY run if b = CInt(a) does NOT cause an exception.
Then in our Catch block we added MyMessage = “Could not make the string ‘a’ into an integer ‘b’.”, This line will ONLY run in b = CInt(a) DOES cause an exception.
We also added in Finally, This will always run.. weather there is an exception or not.
Using Multiple Catch’s
Of course everything is not an InvalidCastException (but everone is an Exception). So you can add multiple Catch statments to one Try.
Lets take a look… we are going to use a new example though, one for retreaving a SqlDataReader from an SQL Database
Dim strSQL As String
Dim SqlConn As Data.SqlClient.SqlConnection
Dim SqlComm As Data.SqlClient.SqlCommand
Dim DR As Data.SqlClient.SqlDataReader
Dim result As String = String.Empty
'Notice we declare our variables outside of the try block, this is so we can use it in the finally block.
Try
strSQL = "SELECT * FROM mytable WHERE mycol=23"
SqlConn = New Data.SqlClient.SqlConnection("Persist Security Info=False;Data Source=__;Initial Catalog=__;User ID=__;Password=__;")
SqlComm = New Data.SqlClient.SqlCommand(strSQL, SqlConn)
SqlConn.Open()
DR = SqlComm.ExecuteReader()
If DR.Read() Then
result = DR.Item("mycol") & "----" & DR.Item("mycol2")
Else
result = "No records found."
End If
Catch ex As System.Data.SqlClient.SqlException
'This will catch SQL statement Errors in your "SELECT" statement and Connectionstring.
result = "There was an SqlException.." & vbCrLf & "Details..." & vbCrLf & ex.ToString()
Catch ex As InvalidCastException
'This will catch Cast exceptions
result = "There was an InvalidCastException..." & vbCrLf & "Details..." & vbCrLf & ex.ToString()
Catch ex As Exception
'This will catch everything else. (except errors in the finally statement)
result = "There was an Unhandled Exception..." & vbCrLf & "Details..." & vbCrLf & ex.ToString()
Finally
'Make sure to use IsNothing or Is Nothing when in Finally,
' you will get "Object Reference" errors if you dont.
If IsNothing(DR) = False Then
If DR.IsClosed = False Then DR.Close()
End If
If IsNothing(SqlComm) = False Then SqlComm.Dispose()
If IsNothing(SqlConn) = False Then
If SqlConn.State <> Data.ConnectionState.Closed Then SqlConn.Close() : SqlConn.Dispose()
End If
MsgBox(result)
End Try
If you run the above code WITH OUT changing ANYTHING.. you will get a msgbox like below..
There was an SqlException..
Details…
System.Data.SqlClient.SqlException: SQL Server does not exist or access denied.
at System.Data.SqlClient.SqlConnection.Open()
This is because “__” is probably not an sqlserver in your LAN.