Section 17.3. The Throw Statement

   

17.3 The Throw Statement

To signal an abnormal condition in a VB.NET program, you throw an exception. To do this, you use the Throw keyword. The following line of code creates a new instance of System.Exception and then throws it:

 Throw New System.Exception( ) 

Example 17-1 illustrates what happens if you throw an exception and there is no try/catch block to catch and handle the exception. In this example, you'll throw an exception even though nothing has actually gone wrong, just to illustrate how an exception can bring your program to a halt.

Example 17-1. Unhandled exception
 Option 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...")             Throw New System.Exception( )             Console.WriteLine("Exit Func2...")         End Sub 'Func2     End Class 'Tester  End Namespace 'ExceptionHandling 
  Output:  Enter Main... Enter Run... Enter Func1... Enter Func2... Unhandled Exception: System.Exception: Exception of type System.Exception was thrown. at DebuggingVB.ExceptionHandling.Tester.Func2( ) in C:...\Module1.vb:line 27    at DebuggingVB.ExceptionHandling.Tester.Func1( )     in C:...\Module1.vb:line 21    at DebuggingVB.ExceptionHandling.Tester.Run( )     in C:...\Module1.vb:line 14    at DebuggingVB.ExceptionHandling.Tester.Main( )     in C:...\Module1.vb:line 8 

This simple example writes to the console as it enters and exits each method. Main( ) calls Run( ) which in turn calls Func1( ). After printing out the Enter Func1 message, Func1( ) immediately calls Func2( ). Func2( ) prints out the first message and throws an object of type System.Exception.

Execution immediately stops, and the CLR looks to see whether a handler is in Func2( ). There is not, and so the runtime unwinds the stack (never printing the exit statement) to Func1( ). Again, there is no handler, and the runtime unwinds the stack back to Main( ). With no exception handler there, the default handler is called, which prints the error message, and terminates the program.

   


Learning Visual Basic. NET
Learning Visual Basic .Net
ISBN: 0596003862
EAN: 2147483647
Year: 2002
Pages: 153
Authors: Jesse Liberty

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net