16.4. The throw StatementTo signal an abnormal condition in a C# program, throw an exception by using the tHRow keyword. The following line of code creates a new instance of System.Exception and then throws it: throw new System.Exception( ); Example 16-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 16-1. Unhandled exception
The output looks like this: Enter Main... Enter Run... Enter Func1... Enter Func2... Unhandled Exception: System.Exception: Exception of type System.Exception was thrown. at ExceptionHandling.Tester.Func2( ) in source\exceptions\exceptionhandling\class1.cs:line 34 at ExceptionHandling.Tester.Func1( ) in source\exceptions\exceptionhandling\class1.cs: line 27 at ExceptionHandling.Tester.Run( ) in source\exceptions\exceptionhandling\class1.cs: line 19 at ExceptionHandling.Tester.Main( ) in source\exceptions\exceptionhandling\class1.cs: line 13
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 if there is a handler 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. |