18.4 The try and catch StatementsTo handle exceptions, take the following steps:
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 blocksusing 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. |