17.4 The Try and Catch StatementsTo handle exceptions, you take the following steps:
A try block is created using the keyword Try and is ended with the keywords End Try . A catch block is created using the Catch keyword. A catch block can be terminated either by the next use of the Catch keyword or by the End Try statement. These constructs are illustrated in Example 17-2. Note that Example 17-2 is the same as Example 17-1 except that a try/catch block has been added. Example 17-2. Try and catch blocksOption Strict On Imports System Namespace ExceptionHandling Class Tester Shared Sub Main( ) Console.WriteLine("Enter Main...") Dim t As New Tester( ) t.Run( ) Console.WriteLine("Exit Main...") End Sub 'Main Public Sub Run( ) Console.WriteLine("Enter Run...") Func1( ) Console.WriteLine("Exit Run...") End Sub 'Run Public Sub Func1( ) Console.WriteLine("Enter Func1...") Func2( ) Console.WriteLine("Exit Func1...") End Sub 'Func1 Public Sub Func2( ) Console.WriteLine("Enter Func2...") Try Console.WriteLine("Entering Try block...") Throw New System.Exception( ) Console.WriteLine("Exitintg Try block...") Catch Console.WriteLine("Exception caught and handled") End Try Console.WriteLine("Exit func2...") End Sub 'Func2 End Class 'Tester End Namespace 'ExceptionHandling Output: Enter Main... Enter Run... Enter Func1... Enter Func2... Entering try block... Exception caught and handled! Exit Func2... Exit Func1... Exit Run... Exit Main... Following the try statement is a generic catch statement. The catch statement in Example 17-2 is generic because you haven't specified what kind of exceptions to catch. If you don't specify a particular exception type, the catch block will catch any exceptions that are thrown. Notice that the Exit statements are now written in the output. With the exception handled, execution resumes immediately after the catch block. In Example 17-2, the catch statement simply reports that the exception has been caught and handled. In a real catch statement, you might take corrective action to fix the problem that caused an exception to be thrown. For example, if the user is trying to open a read-only file, you might invoke a method that allows the user to change the attributes of the file. If the program has run out of memory, you might give the user an opportunity to close other applications. If all else fails, the catch block can print an error message so that the user knows what went wrong. Using catch statements to catch specific types of exceptions is discussed later in this chapter. |