Answers to Chapter 19 Review Questions


Chapter 19


List three examples of typical exceptions.


Dividing by zero, running out of memory, accessing a non-existent file.


What are the advantages of handling exceptions with try-catch-finally?


The normal case code and exception handling code can be kept separate. Exceptions can be handled gracefully without exposing the end user to cryptic looking code.


Which class is at the top of the exceptions class hierarchy?




How many catch and finally blocks can be attached to a try block?


Zero, one or many catch blocks, and zero or one finally block. However, at least one block (it can either be a catch or a finally block) must be attached to a try block.


What happens to normal execution flow when an exception is thrown inside a try block?


Normal execution is terminated. The program will move quickly out through the various method calls looking for a matching catch statement. If a matching catch block is found, normal execution continues from here; otherwise, the exception is caught by the runtime and the program is abruptly terminated.


How can a catch block match an exception?


By being the same class or an ancestor class of the exception object class that was thrown.


If no abnormal conditions were experienced, where is the flow of execution transferred after a try block has finished executing?


If the try block has an associated finally block, this block will be executed. If no finally block exists for the try block, execution begins after the last catch block.


What happens if an exception is thrown in a try block but no matching catch blocks are found?


Then the runtime will look for a matching catch statement by unraveling the current method call chain. If none is found, the runtime will handle the exception itself.


What happens if a catch block throws an exception?


The search will continue for a catch block that matches the exception thrown in the catch block.


What is the purpose of the finally block?


It guarantees to execute the code contained in its block, regardless of whether or not an exception has been thrown.


Which class must you derive from to write your own custom-made exception classes?




Is the following try-finally construct valid? If so, why would you ever want to implement it?

 try { ...} finally { ...} 

Yes, it is valid. This construct is sometimes used when a method has many return statements but a core set of statements must be executed before the method ends, regardless of the return statement the method exits with.


Is the following try-catch construct valid? Why or why not?

 try { ...} catch (System.Exception exObj) { ...} catch (System.IndexOutOfRangeException exObj) { ...} 

No, it is invalid. The last catch statement will never be executed because System.Exception is an ancestor to System.IndexOutOfRangeException.


What happens if an exception finds no matching catch blocks in your program?


The runtime's default exception handler will handle the exception and abruptly terminate the program.

Answers to Chapter 19 Programming Exercises


Implement the necessary exception handling code in Listing 19.1 to prevent the program from stopping abruptly and allow (in a user-friendly manner) the user to assign a value to yourInt in Method2.

Programming exercises 2 4 build on the same program, so please save the program in each exercise.


Exercise 1: See Listing 19.2 for the answer.


Write a class called Meteorologist that contains an array named rainfall containing 12 elements (of type int). Write a constructor for the class that assigns an arbitrary number to each of the 12 elements in rainfall. Include a method with the following header in Meteorologist:

 public int GetRainfall(int index) 

This method must return the value of the element in rainfall that corresponds to the given index. Include the necessary code in GetRainfall to handle any out-of-range exceptions thrown from within the GetRainfall method. Implement code to test the Meteorologist class and its method.


During each month, a reading is made for the total amount of pollution absorbed into the rainwater from the air and brought to the ground. Include another array in Meteorologist called pollution, also with 12 elements of type int. Use the constructor from exercise 2 to assign arbitrary values to these 12 elements. Write a method with the header

 public int GetAveragePollution(int index) 

which calculates the average amount of pollution in each unit of rainfall for a given month. For example, to calculate the average pollution in month 4 per rainfall unit, perform the following calculation:

 averagePollution = pollution[3] / rainfall[3] 

Implement the necessary exception handling code for GetAveragePollution. Notice that both an index out-of-range exception as well as a divide by zero exception can be thrown in this method.


The GetAveragePollution method from exercise 3 opens a file on its entry. This file must always be closed before the method exits. Make sure that this is the case. You can pretend the file is being closed with the following line:

 Console.WriteLine("Closing WeatherXYZ file"); 

Exercises 2 4:

 using System; class Meteorologist {     private int[] rainfall;     private int[] pollution;     public Meteorologist()     {         rainfall = new int[12];         pollution = new int[12];          //Assign an arbitrary number to each          //rainfall and pollution element.          //In this case rainfall is set to          //i * 5 and pollution to i + 10         for(int i = 0; i < 12; i++)         {             rainfall[i] = i * 5;             pollution[i] = i + 10;         }     }     public int GetRainfall(int index)     {         try         {             return rainfall[index];         }         catch(IndexOutOfRangeException exObj)         {             Console.WriteLine("The index must be between 0 and 11");             Console.WriteLine(exObj.Message);             return -1;         }     }     public int GetAveragePollution(int index)     {         Console.WriteLine("Opening WeatherXYZ file");         try         {             return pollution[index] / rainfall[index];         }         catch(IndexOutOfRangeException exObj)         {             Console.WriteLine("The index must be between 0 and 11");             Console.WriteLine(exObj.Message);             return -1;         }         catch(DivideByZeroException exObj)         {             Console.WriteLine("The rainfall element was zero");             Console.WriteLine(exObj.Message);             return -1;         }         finally         {             Console.WriteLine("Closing WeatherXYZ file");         }     } } class Tester {     public static void Main()     {         Meteorologist aMeteorologist = new Meteorologist();         Console.WriteLine("Rainfall in January: {0}", aMeteorologist.GetRainfall(0));          //Triggering IndexOutOfRangeException         Console.WriteLine("Rainfall next year: {0}", aMeteorologist.GetRainfall(13));          //Triggering DivideByZeroException         Console.WriteLine("Average pollution: {0}",  graphics/ccc.gifaMeteorologist.GetAveragePollution(0));     } } 


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: