Exception Handling

Exercise 1: Bounds Checking Array
In the array class we created previously, the bounds checking was very basic. There was no error generated, but setting an element was ignored or the first element was returned. Obviously you want to know if there was an out of bounds error. This is possible by exception handling. Change the Array class to throw exceptions:
•In the GetElement(), SetElement() and index operator throw -1 if the index was toosmall or too big.
•In the main program, create an Array object and access an element that does not exist.Run the program. What happens?
•The exception must be caught, so place the code inside a try … catch block thatcatches an int.
•In the catch handler, print an error message.

Exercise 2: Exception Objects
Throwing an int is an easy solution. But exception handling is also object oriented and allows us to throw an object. In this exercise we will create an exception hierarchy with an ArrayException base class and an OutOfBoundsExceptionderived class as shown in Figure 3:
•You can implement both exception classes in the header file for simplicity.
•Give the ArrayException an abstract GetMessage() function that returns a std::string.
•Give the OutOfBoundsException class a constructor with an int as argument thatindicates the erroneous array index and store it in a data member.
•Override the GetMessage() function and let the implementation return a messagestring saying the given index is out of bounds.
•In the Array class, throw now a OutOfBoundsException object instead of an integer.
•Change the main program so that it catches the ArrayException base class and usesthe GetMessage() function to display an error message.

Leave a Reply

Your email address will not be published. Required fields are marked *