Section A.16. Chapter 16: Throwing and Catching Exceptions


A.16. Chapter 16: Throwing and Catching Exceptions

A.16.1. Quiz



Solution to Question 161 .

An exception is an object (derived from System.Exception ) that contains information about a problematic event. The framework supports throwing exceptions to stop processing and catching events to handle the problem and resume processing.



Solution to Question 162 .

The stack is unwound until a handler is found, or else the exception is handled by the CLR, which terminates the program.



Solution to Question 163 .

You create a try / catch block; the catch part is the exception handler.



Solution to Question 164 .

The syntax is:

 throw new Sytem.Arg'umentNullException(  ) 



Solution to Question 165 .

You can write multiple exception handlers to handle different exceptions; the first handler that catches the thrown exception will prevent further handling. Beware of inheritance complications in the ordering of your handlers.



Solution to Question 166 .

If you have code that must run whether or not an exception is thrown (to close a file, for example), place that code in the finally block. You must have a try for the finally , but a catch is optional.

A.16.2. Exercises



Solution to Exercise 16-1 .

Create a Cat class with one int property: Age . Write a program that creates a List of Cat objects in a try block. Create multiple catch statements to handle an ArgumentOutOfRangeException , and an unknown exception, and a finally block to simulate deallocating the Cat objects. Write test code to throw an exception that you will catch and handle.

 using System; using System.Collections.Generic; namespace ConsoleApplication1 {    class Cat    {       private int age;       public int Age       {          get { return age; }          set { age = value; }       }       public Cat( int age )       {          this.age = age;       }    }    class Tester    {       private void CatManager(Cat kitty)       {          Console.WriteLine ("Managing a cat who is " + kitty.Age +                             " years old");       }       public void Run(  )       {          try          {             Console.WriteLine(               "Allocate resource that must be deallocated here" );             List<Cat> cats = new List<Cat>(  );             cats.Add( new Cat( 5 ) );             cats.Add( new Cat( 7 ) );             CatManager( cats[1] ); // pass in the second cat             CatManager( cats[2] ); // pass in the non-existent third cat             Console.WriteLine(             "This line may or may not print" );          }          catch ( System.ArgumentOutOfRangeException )          {             Console.WriteLine(            "I've often seen a cat without a smile, \nbut this is " +            "the first time I've seen a smile without a cat" );          }          catch (Exception e)          {             Console.WriteLine( "Unknown exception caught"  + e.Message);          }          finally          {             Console.WriteLine( "Deallocation of resource here." );          }       }       static void Main(  )       {          Console.WriteLine( "Enter Main..." );          Tester t = new Tester(  );          t.Run(  );          Console.WriteLine( "Exit Main..." );       }    } } 

The output from this example would look like this:

 Enter Main... Allocate resource that must be deallocated here Managing a cat who is 7 years old I've often seen a cat without a smile, but this is the first time I've seen a smile without a cat Deallocation of resource here. Exit Main... 

Your output may vary, depending on how you wrote your test code.



Solution to Exercise 16-2 .

Modify Exercise 16-1 so that it does not throw an error. Create a custom error type CustomCatError that derives from System.ApplicationException , and create a handler for it. Add a method to CatManager that checks the cat's age, and throws an error of type CustomCatError if the age is less than or equal to 0, with an appropriate message.

 using System; using System.Collections.Generic; namespace ConsoleApplication1 {     class Cat     {         private int age;         public int Age         {             get { return age; }             set { age = value; }         }         public Cat(int age)         {             this.age = age;         }     }     // custom exception class     public class CustomCatException :     System.ApplicationException     {         public CustomCatException(string message)             :         base(message) // pass the message up to the base class         {         }     }     class Tester     {         private void CheckCat(Cat testCat)         {             if (testCat.Age <= 0)             {                 // create a custom exception instance                 CustomCatException e =                 new CustomCatException("Your cat does not exist");                 e.HelpLink =                 "http://www.libertyassociates.com/NoZeroDivisor.htm";                 throw e;             }         }         private void CatManager(Cat kitty)         {             CheckCat(kitty);             Console.WriteLine("Managing a cat who is " + kitty.Age +                               " years old");         }         public void Run(  )         {             try             {                 Console.WriteLine("Allocate resource that must be deallocated                                    here");                 List<Cat> cats = new List<Cat>(  );                 cats.Add(new Cat(7));                 cats.Add(new Cat(-2));                 CatManager(cats[0]); // pass in the first cat                 CatManager(cats[1]); // pass in the second cat                 Console.WriteLine(                 "This line may or may not print");             }             // catch custom exception             catch (CustomCatException e)             {                 Console.WriteLine(                 "\nCustomCatException! Msg: {0}",                 e.Message);                 Console.WriteLine(                 "\nHelpLink: {0}\n", e.HelpLink);             }             catch (System.ArgumentOutOfRangeException)             {                 Console.WriteLine(                "I've often seen a cat without a smile, \nbut this is " +                "the first time I've seen a smile without a cat");             }             catch (Exception e)             {                 Console.WriteLine("Unknown exception caught" + e.Message);             }             finally             {                 Console.WriteLine("Deallocation of resource here.");             }         }         static void Main(  )         {             Console.WriteLine("Enter Main...");             Tester t = new Tester(  );             t.Run(  );             Console.WriteLine("Exit Main...");         }     } } 



Learning C# 2005
Learning C# 2005: Get Started with C# 2.0 and .NET Programming (2nd Edition)
ISBN: 0596102097
EAN: 2147483647
Year: 2004
Pages: 250

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