// Your code
Catch [ErrorParameter] [As ErrorType]
[ Finally ]
//code that executes even if runtime exceptions were raised
Optional, used to determine the type of runtime exception.
Optional, if used, it must be used with ErrorParameter. Used to '“catch” a particular type of runtime error. If used, the Try statement will handle only that type of runtime error.
The Try statement is similar to the Exception statement. Exceptions that occur within the Try statement are caught by the Catch statement. It has the same syntax as the Exception statement. See the RuntimeException statement or the Runtime Errors theme for descriptions of each type of runtime error.
Unlike the Exception statement, Try statements can be nested. If a Try statement does not handle an exception or re-raises it, it can be handled by the next outermost Try statement, or by the Exception statement itself if there are no containing Try statements.
This example uses the Catch statement in a window's Opening event handler to handle out of memory exceptions when trying to draw an imported gif image. The variable MyPicture is a global property of type Picture. The picture "Logo" has been added to the Project.
Try MyPicture = New Picture(Logo.Width, Logo.Height) MyPicture.Graphics.DrawPicture(Logo, 0, 0) Catch err As OutOfMemoryException MessageBox("Insufficient memory to draw the picture!") End Try
The following example handles an attempt to access a nonexistent value in a Dictionary.
Try someValue = myDict.Value("doesn't exist") Catch err As KeyNotFoundException MessageBox("The requested key does not exist.") End Try
The following catches any exception in the code block:
Try Var d As DateTime Var day As Integer = d.Day // NilObjectException will be caught below Catch e As RunTimeException If e IsA EndException Or e IsA ThreadEndException Then Raise e // Re-raise the exception for the framework End If MessageBox(e.Message) End Try
All project types on all supported operating systems.