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:
Execute any code that you suspect might throw an exception
(such as code that opens a file or allocates memory) within a
try
block.
Catch any exceptions that are thrown in a catch
block.
A try
block is created using
the keyword try
and is enclosed in
braces. The try
block is 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. 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. Try and catch blocks
using System; namespace TryAndCatchBlocks { 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..." ); try { Console.WriteLine( "Entering try block..." ); throw new ApplicationException( ); // this code never executes because of the exception Console.WriteLine( "Exiting try block..." ); } catch { Console.WriteLine( "Exception caught and handled!" ); } Console.WriteLine( "Exit Func2..." ); } } }
The output looks like this:
Enter Main... Enter Run... Enter Func1... Enter Func2... Entering try block... Exception caught and handled! Exit Func2... Exit Func1... Exit Run... Exit Main...
Following the try
statement is
the catch
statement. In a real
catch
statement, you might silently
fix the problem (for example, by retrying a database connection), or you
might 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
statement simply reports that
the exception has been caught and handled.
Notice that the exit statements are now written. With the
exception handled, execution resumes immediately after the catch
block.