DekGenius.com
Team LiB   Previous Section   Next Section

18.3 The throw Statement

To 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 18-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 18-1. Unhandled exception
using System;

namespace ExceptionHandling
{
   class Tester
   {

      static void Main()
      {
          Console.WriteLine("Enter Main...");
          Tester t = new Tester();
          t.Run();
          Console.WriteLine("Exit Main...");           
      }
      public void Run()
      {
          Console.WriteLine("Enter Run...");
          Func1();
          Console.WriteLine("Exit Run...");           
      }

       public void Func1()
       {
           Console.WriteLine("Enter Func1...");
           Func2();
           Console.WriteLine("Exit Func1...");           
       }

       public void Func2()
       {
           Console.WriteLine("Enter Func2...");
           throw new System.Exception();
           Console.WriteLine("Exit Func2...");
       }

   }
}
Output:
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.

    Team LiB   Previous Section   Next Section