Udostępnij za pośrednictwem


Try...Catch...Finally Statement (Visual Basic)

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 ]
    [ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
    [ catchStatements ]
    [ Exit Try ] ]
[ Catch ... ]
[ Finally
    [ finallyStatements ] ]
End Try

Parts

  • tryStatements
    Optional. Statement(s) where an error can occur. Can be a compound statement.

  • Catch
    Optional. Multiple Catch blocks permitted. If an exception occurs when processing the Try block, each Catch statement is examined in textual order to determine whether it handles the exception, with exception representing the exception that has been thrown.

  • exception
    Optional. Any variable name. The initial value of exception is the value of the thrown error. Used with Catch to specify the error caught. If omitted, the Catch statement catches any exception.

  • type
    Optional. Specifies the type of class filter. If the value of exception is of the type specified by type or of a derived type, the identifier becomes bound to the exception object.

  • When
    Optional. A Catch statement with a When clause catches exceptions only when expression evaluates to True. A When clause is applied only after checking the type of the exception, and expression may refer to the identifier representing the exception.

  • expression
    Optional. Must be implicitly convertible to Boolean. Any expression that describes a generic filter. Typically used to filter by error number. Used with When keyword to specify circumstances under which the error is caught.

  • catchStatements
    Optional. Statement(s) to handle errors that occur in the associated Try block. Can be a compound statement.

  • Exit Try
    Optional. Keyword that breaks out of the Try...Catch...Finally structure. Execution resumes with the code immediately following the End Try statement. The Finally statement will still be executed. Not allowed in Finally blocks.

  • Finally
    Optional. A Finally block is always executed when execution leaves any part of the Try statement.

  • finallyStatements
    Optional. Statement(s) that are executed after all other error processing has occurred.

  • End Try
    Terminates the Try...Catch...Finally structure.

Remarks

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.

The Try block contains code where an error can occur, and 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 a class that derives from the Exception class. The Exception class instance corresponds to the error that occurred in the Try block. The instance contains information about the error. This includes, among other things, its number and message.

If a Catch statement does not specify an exception argument, it catches any kind of system or application exception. You should always use this variation as the last Catch block in the Try...Catch...Finally structure, after catching all the specific exceptions you anticipate. Control flow can never reach a Catch block that follows a Catch without an exception argument.

In partial-trust situations, such as an application hosted on a network share, Try...Catch...Finally does not catch security exceptions that occur before the method that contains the call is invoked. The following example, when you put it on a server share and run from there, produces the error "System.Security.SecurityException: Request Failed." For more information about security exceptions, see the SecurityException class.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click
    Try
        Process.Start("https://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 have to put the Process.Start statement in a separate Sub. The initial call to the Sub will fail. This enables Try...Catch to catch it before the Sub that contains Process.Start is started and the security exception produced.

Note

If a Try statement does not contain at least one Catch block, it must contain a Finally block.

Example

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 = 0
    Try                    ' Set up structured error handling.
        x = x \ y          ' Cause a "Divide by Zero" error.
    Catch ex As Exception When y = 0        ' Catch the error.
        Beep()
        MsgBox("You tried to divide by 0.") ' Show an explanatory message.
    Finally
        Beep()             ' This line is executed no matter what.
    End Try 
End Sub

See Also

Reference

End Statement

Err Object (Visual Basic)

Exit Statement (Visual Basic)

On Error Statement (Visual Basic)

Exception

GoTo Statement