抛出类类型作为异常

throwing a class type as an exception

本文关键字:异常 类型      更新时间:2023-10-16
class error
{
    int x;
    int y; 
public:
    error() { }
    error(int a,int b)
    {
        x=a;
        y=b;
    }
    void display()
    {
        cout<<x<<endl<<y;
    }
};
main()
{
    error e;
    try{
        cout<<"press any key to test exceptionn";
        getch();
        throw error(99,22);
    }
    catch(error e)
    {
        cout<<"nexception caught successfullyn";
        e.display();
    }
}

throw error(99,22),该语句如何将类对象抛出到catch块?如果我们写"throw e;",那么可以理解将抛出一个对象,但是"throw error();"将只调用该类的构造函数,那么这段代码是如何工作的呢?

总是可以通过调用构造函数来提供临时对象。

假设我有一个类Frac来存储有理数。它支持+、-、*和/等。

如果我要计算(1/3 + 9/4)我可以把它写成

Frac ans = Frac(1,3) + Frac(9,4);

从函数返回对象也是如此:

Frac Frac::one() {
    return Frac(1, 1);
}

或者甚至抛出异常,正如你的用例:

throw std::logic_error("This is a call to logic_error's constructor");

另一个提示,你应该总是在c++中"按引用"捕获异常,像这样:

catch (error & e) { /*...*/ }

这样做的原因是得到正确的多态行为的情况下,你有子类重新实现虚函数在你的异常类