Handling Derived-Class Exceptions. McGraw-Hill The Complete Reference Fourth Edition
Reklama
Reklama
C h a p t e r 1 9 : E x c e p t i o n H a n d l i n g
497
Handling Derived-Class Exceptions
You need to be careful how you order your catch statements when trying to catch exception types that involve base and derived classes because a catch clause for a base class will also match any class derived from that base. Thus, if you want to catch exceptions of both a base class type and a derived class type, put the derived class first in the catch sequence. If you don't do this, the base class catch will also catch all derived classes. For example, consider the following program.
// Catching derived classes.
#include <iostream> using namespace std; class B {
}; class D: public B {
}; int main()
{
D derived; try { throw derived;
} catch(B b) { cout << "Caught a base class.\n";
} catch(D d) { cout << "This won't execute.\n";
}
} return 0;
Here, because derived is an object that has B as a base class, it will be caught by the first catch clause and the second clause will never execute. Some compilers will flag this condition with a warning message. Others may issue an error. Either way, to fix this condition, reverse the order of the catch clauses.
Stiahnuť
Reklama