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

Get Learning C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.