Intermediate Business Programming with C++
From examples above we know that any programmer data types may be thrown and they can appear as the arguments of a catch() statement. The question is: Are there any differences when class inheritance is introduced into this type of program? For example what happens when an object of the base class and an object of a derived class are each thrown. Further suppose that there is a different catch() for each of these two types. Does it make a difference which catch() is listed first: the one whose argument is the base or the one with the argument which is a derived class?
For example see ratio.cpp. In this example the catch() for the base class was listed first. When the base object was thrown, the correct catch() was called. However when the derived object was thrown, the base argument catch() was called and the derived argument catch() would never be called. (Notice the warning in the Visual Studio .NET C++ compiler that tells you of this problem.)
Now look at the example ratio2.cpp. This example is the same as ratio.cpp above except that the two different catch() statements are switched. In this example the catch() with the derived argument was listed first. In this example the base object calls the catch() with the base object argument while the catch() with the derived argument was called when the derived object was thrown. So it makes a difference the order of catch() statements when dealing with inheritance.
When a program has to handle both derived and base objects, the catch() with the derived object argument should be listed first after the try{} block.
Категории