. 异常类继承关系
class Exception {
private:
string error;
public:
virtual string getError();
virtual void setError(string e);
virtual string toString();
Exception();
};
class ZeroException : public Exception {
public:
ZeroException() {
setError("the divisor is zero!");
}
};
class InputException : public Exception {
public:
InputException() {
setError("the input number is negative error!");
}
};
class NoTriangleException : public Exception {
public:
NoTriangleException() {
setError("Three numbers cannot form a triangle!");
}
};
ZeroException
、InputException
和NoTriangleException
都是Exception
的子类,它们继承了Exception
类中定义的虚函数,包括toString()
。- 当在
Triangle
类的构造函数中抛出这些异常时,它们会被作为Exception
类型的对象抛出。由于它们是Exception
类的子类,因此可以通过Exception&
类型的引用捕获。
2. 异常的捕获和处理
在 main
函数中的异常处理部分:
int main(int argc, char* argv[]) {
double t1, t2, t3;
cin >> t1 >> t2 >> t3;
try {
Triangle tri(t1, t2, t3); // 可能会抛出 ZeroException、InputException 或 NoTriangleException
cout << "area=" << tri.area();
}
catch (Exception& e) { // 捕获所有继承自 Exception 的异常
cout << e.toString(); // 调用 toString() 打印异常信息
}
return 0;
}
catch (Exception& e)
:这里使用了基类Exception
的引用来捕获异常。由于ZeroException
、InputException
和NoTriangleException
都是Exception
的子类,因此当抛出的异常类型是这些子类时,可以被Exception&
类型的引用捕获。- 在捕获到异常后,通过调用
e.toString()
可以获取异常对象的描述信息,这是因为toString()
是虚函数,能够在运行时根据对象的实际类型来调用相应的实现。
因此,通过这种继承和多态的设计,你可以在捕获异常时,根据具体的异常类型来处理不同的异常情况,并且能够统一地使用基类 Exception
的接口来获取异常信息,使得异常处理更加灵活和可维护。