This documentation is archived and is not being maintained.

How to: Catch an Exception in Visual Basic .NET

This section describes how to catch an SMO exception in Visual Basic.

The code example shows how to use the Try…Catch…Finally Visual Basic .NET statement to catch a SMO exception. All SMO exceptions have the type SmoException and are listed in the SMO reference. The sequence of inner exceptions is displayed to show the root of the error. For more information, see the Visual Basic .NET documentation.

  1. Start Visual Studio 2005.

  2. From the File menu, select New Project. The New Project dialog box appears.

  3. In the Project Types pane, select Visual Basic. In the Templates pane, select Console Application.

  4. (Optional) In the Name box, type the name of the new application.

  5. Click OK to load the Visual Basic console application template.

  6. On the Project menu, select Add Reference item. The Add Reference dialog box appears. Select Browse and locate the SMO assemblies in the C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies folder. Select the following files:





  7. On the View menu, click Code.-Or-Select the Module1.vb window to display the code window.

  8. In the code, before any declarations, type the following Imports statements to qualify the types in the SMO namespace:

    Imports Microsoft.SqlServer.Management.Smo
    Imports Microsoft.SqlServer.Management.Common
  9. Insert the code that follows this procedure into the main program.

  10. Run and build the application.

'This sample requires the Microsoft.SqlServer.Management.Smo.Agent namespace is included.
'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
'Define an Operator object variable by supplying the parent SQL Agent and the name arguments in the constructor.
'Note that the Operator type requires [] parenthesis to differentiate it from a Visual Basic key word.
Dim op As [Operator]
op = New [Operator](srv.JobServer, "Test_Operator")
'Start exception handling.
    'Create the operator again to cause an SMO exception.
    Dim opx As OperatorCategory
    opx = New OperatorCategory(srv.JobServer, "Test_Operator")
    'Catch the SMO exception
Catch smoex As SmoException
    Console.WriteLine("This is an SMO Exception")
    'Display the SMO exception message.
    'Display the sequence of non-SMO exceptions that caused the SMO exception.
    Dim ex As Exception
    ex = smoex.InnerException
    Do While ex.InnerException IsNot (Nothing)
        ex = ex.InnerException
    'Catch other non-SMO exceptions.
Catch ex As Exception
    Console.WriteLine("This is not an SMO exception.")
End Try