As you saw, the exception in your previous example stopped your program dead. That’s usually not the desired behavior. What you need is a way to tell the compiler, “If any exceptions are thrown in this section of code, take this action.” That way, your program can continue on from the error or at least end gracefully. This process is called handling the exception. To handle exceptions, take the following steps:
A try
block is created using the keyword try
and is enclosed in braces. You don’t need any extra code to create the try
block; it just indicates the area of code where you want to watch for exceptions. A catch
block holds the code where you take action based on the type of exception thrown. It is created using the keyword catch
and is also enclosed in braces. In the abstract, the try
/catch
block looks like this:
try { // Potentially hazardous code goes here. } catch { // Exception handler code goes here. }
Example 16-2 illustrates these constructs. Note that Example 16-2 is identical to Example 16-1 except that now the program includes a try/catch
block.
Example 16-2. The try and catch blocks in this example let you avoid the crash of the previous example
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Example_16_2_ _ _ _try_and_catch_blocks { 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..."); try { Console.WriteLine("Entering try block..."); throw new System.Exception(); // this next line can never execute Console.WriteLine("Exiting try block..."); } catch { Console.WriteLine("Exception caught and handled!"); } Console.WriteLine("Exiting Method2..."); } static void Main() { Console.WriteLine("Entering Main..."); Tester t = new Tester(); t.Run(); Console.WriteLine("Exiting Main..."); } } }
Entering Main... Entering Run... Entering Method1... Entering Method2... Entering try block... Exception caught and handled! Exiting Method2... Exiting Method1... Exiting Run... Exiting Main...
Following the try
block is the catch
block. In a real catch
statement, you would try to include code to fix the problem—if you can fix it without interrupting the user, so much the better. For example, if the exception is raised because a database connection is down, you might retry the connection, assuming it’s safe to do so. You might also interact with the user to solve the problem, such as offering the user the opportunity to close other applications and free up memory. In Example 16-2, the catch
block simply reports that the exception has been caught and handled.
Notice that all the exit statements are now written. With the exception handled, execution resumes immediately after the catch
block.