Section 18.4. The try and catch Statements

   

18.4 The try and catch Statements

To handle exceptions, take the following steps:

  1. Execute any code that you suspect might throw an exception (such as code that opens a file or allocates memory) within a try block.

  2. Catch any exceptions that are thrown in a catch block.

A try block is created using the keyword try and is enclosed in braces. A catch block is created using the keyword catch and is also enclosed in braces. Example 18-2 illustrates these constructs. Note that Example 18-2 is identical to Example 18-1 except that now the program includes a try/catch block.

Example 18-2. Try and catch blocks
 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...");  try   {   Console.WriteLine("Entering try block...");   throw new System.Exception();   Console.WriteLine("Exiting try block...");   }   catch   {   Console.WriteLine("Exception caught and handled!");   }  Console.WriteLine("Exit Func2...");        }    } }  Output:  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 (e.g., retry a database connection), or you might interact with the user to solve the problem (e.g., offer the user the opportunity to close other applications and free up memory). In Example 18-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.

   


Learning C#
Learning C# 3.0
ISBN: 0596521065
EAN: 2147483647
Year: 2005
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net