The throw Statement
Most of the time, the system generates exceptions for you. However, you can also generate your own exceptions, and that’s useful for the purposes of demonstration in this chapter, so we’ll show you how to do that first. To signal an abnormal condition in a C# program, you 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();
Remember that exceptions are objects in C#, not simply messages, so the throw statement here actually creates a new Exception object, which is why it looks like it’s calling a constructor. Example 16-1 illustrates what happens if you throw an exception and there is no exception handler 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. The unhandled exception in this example will crash your program, which is what you’re trying to avoid
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Example_16_1_ _ _ _Unhandled_Exception { class Tester { public void Run() { Console.WriteLine("Entering Run..."); Method1(); Console.WriteLine("Exiting Run..."); } public void Method1() { Console.WriteLine("Entering Method1..."); Method2(); Console.WriteLine("Exiting Method1..."); } public void Method2() { Console.WriteLine("Entering Method2..."); throw ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access