使用Throw和Catch进行未处理的异常运行时错误

时间:2015-10-23 15:52:34

标签: c++ error-handling runtime-error

所以我认为我理解Throw and Catch但我不确定。我正在使用它来捕获除零错误,并在线查看其他示例,但每次我尝试它时都会抛出一个无法解决的异常错误。我根据我的赋值在构造函数中使用throw函数,然后尝试在int main中捕获它。有谁知道为什么我得到关于未处理异常的运行时错误? 构造

Rational(int n, int d)
{       
    num = n;
    denom = d;
    normalize();

    if (d == 0) {
        throw "Divide by Zero";     
    }       
}

Int Main()代码

int main()
{
int case_count, a, b, c, d;
cin >> case_count;

for (int i = 0; i < case_count; ++i) {
    cout << "Case " << i << "\n";
    cin >> a;
    cin >> b;
    cin >> c;
    cin >> d;
    Rational frac1(a, b);
    Rational frac2(c, d);
    Rational add;
    Rational sub;
    Rational mult;
    Rational div;

    try {
        add = frac1 + frac2;
        sub = frac1 - frac2;
        mult = frac1 * frac2;
        div = frac1 / frac2;


    }
    catch (const char* msg) {
        cout << msg;

    }
    cout << add << " ";
    cout << sub << " ";
    cout << mult << " ";
    cout << div << " ";
    cout << (frac1 < frac2) << "\n";
    cout << frac1.toDecimal() << " ";
    cout << frac2.toDecimal() << "\n";

}
return 0;

}

2 个答案:

答案 0 :(得分:0)

Rational构造函数抛出异常,因此,必须在try语句中创建Rational对象。您正在此语句之外创建许多对象,因此此处抛出的任何异常都是未处理的。

您需要在try语句中创建对象。另外,正如您在OP中所评论的那样,您需要以更好的方式处理异常:

Rational::Rational(int n, int d)
{       
    num = n;
    denom = d;
    normalize();

    if (d == 0) {
        throw std::overflow_error("Divide by zero exception");
    }       
}

然后做:

try {
    Rational frac1(a, b);
    Rational frac2(c, d);
    Rational add;
    Rational sub;
    Rational mult;
    Rational div;

    add = frac1 + frac2;
    sub = frac1 - frac2;
    mult = frac1 * frac2;
    div = frac1 / frac2;
}
catch (std::overflow_error e) {
    cout << e.what();
}

答案 1 :(得分:0)

您在构造函数中抛出异常,特别是需要两个int的异常。因此,您必须将该代码放在try块中。

E.g。

try {
    Rational frac1(a, b);
}
catch (const char* msg) {
    cout << msg;

}