You are on page 1of 2

Programming Techniques Sheet #7

CMP 103 & CMP N103 1/2 Spring 2013






1.
a. Create three unrelated empty classes Except1, Except2, and Except3 to represent three
different exceptions.

b. Write a function TroubleMaker(int n) that throws an exception as follow
i. If n = 1, throw an exception of type Except1.
ii. If n = 2, throw an exception of type Except2.
iii. If n = 3, throw an exception of type Except3.
iv. Otherwise, throw an integer value.

c. In the function definition, write exception specifications showing that the function can
only throw three types of exceptions; Except1, Except2, and Except3.

d. Write a main function that contains the following for loop. To throw all the exceptions
described above.




e. Run the program and observe what will happen.

2. Now modify the main function code (from problem 1) to handle the exceptions.
a. Write three handlers for the above three types of exceptions. Each handler should just
print a message about the type of the exception that was caught. (e.g. "Except1 was
caught")
b. Enclose the above for loop in a try block.
c. How many exceptions could be caught after these modifications?
d. Run the program to check your answer. What is the output?

3. Now, it is required to be able to handle the three exceptions described above.
a. For the main function from problem 2, move the for loop header out of the try block and
leave the handlers as in problem 2.

b. How many exceptions could be caught after these modifications?
c. Run the program to check your answer. What is the output?

4. Modify the for loop in problem 3 to be as follow:



a. What is the output of the program?
b. What is the problem now? Why?
c. Suggest three different methods to solve the above problem.
d. Write a code to implement your suggested solutions.
Cairo University
Faculty of Engineering
CMP 103 & CMP N103

Programming Techniques
Sheet #7
for(int i=1; i<=3; i++)
try
{
TroubleMaker(i);
}
for(int i=1; i<=3; i++)
TroubleMaker(i);
for(int i=1; i<=4; i++)
Programming Techniques Sheet #7

CMP 103 & CMP N103 2/2 Spring 2013



5.
a. For the three classes described in problem 1, inherit class Except2 from Except1 and
Except3 from Except2.
b. Apply these modifications to problem 4 and run the program.
c. What is the output? What is the problem? How to solve it using the three handlers?
d. Show how the problem can be solved by making use of the relation between the three
classes (Use polymorphism).


6. When is the exception object itself created, and when is it destroyed?
a. Add constructors and destructors to the classes Except1, Except2, and Except3. They
should just print messages indicating which class is being constructed / destructed.
b. Add the message "TroubleMaker is called" at the beginning of the TroubleMaker
function.
c. Apply these modifications to problem 5 and run the program.

7. Think: What if the constructor of the exception object itself throws an exception.

You might also like