Provides a way to handle some or all possible errors that may occur in a given block of code, while still running code.
Try [ tryStatements ] [ Catch [ exception [ As type ] ] [ When expression ] [ catchStatements ] ] [ Exit Try ] ... [ Finally [ finallyStatements ] ] End Try
Local variables from a Try block are not available in a Catch block because they are separate blocks. If you want to use a variable in more than one block, declare the variable outside the Try...Catch...Finally structure.
If errors occur that the programmer has not handled, Visual Studio for Applications simply provides its normal error message to a user, as if there was no error handling.
The Try block contains code where an error can occur, while the Catch block contains code to handle any error that does occur. If an error occurs in the Try block, program control is passed to the appropriate Catch statement for disposition. The exception argument is an instance of the Exception class or an instance of a class that derives from the Exception class corresponding to the error that occurred in the Try block. The Exception class instance contains information about the error including, among other things, its number and message.
In partial trust situations, such as an application hosted on a network share, Try...Catch...Finally will not catch security exceptions that occur before the method containing the call is invoked. The following example, when placed on a server share and run from there, for example, will produce the error: "Sub System.Security.SecurityException: Request Failed. For more information on Security Exceptions, see
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click
Try
Process.Start("http://www.microsoft.com")
Catch ex As Exception
MsgBox("Can't load Web page" & vbCrLf & ex.Message)
End Try
End Sub
In such a partial trust situation, you would need to put the Process.Start statement in a separate Sub. The initial call to the Sub will fail, allowing Try...Catch to catch it before the Sub containing Process.Start is launched and the security exception produced.
Note If a Try statement does not contain at least one Catch block it must contain a Finally block.
The following simplified example illustrates the structure of the Try...Catch...Finally statement:
Public Sub TryExample() Dim x As Integer = 5 ' Declare variables. Dim y As Integer = 0Try' Set up structured error handling. x /= y ' Cause a "Divide by Zero" error.Catchex As Exception When y = 0 ' Catch the error. MsgBox(ex.toString) ' Show friendly error message.FinallyBeep() ' Beep after error processing. End Try End Sub
End Statement | Err Object | Exit Statement | On Error Statement |