【问题标题】:Unhandled exception runtime error using Throw and Catch使用 Throw 和 Catch 未处理的异常运行时错误
【发布时间】:2015-10-23 15:52:34
【问题描述】:

所以我想我理解 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;

}

【问题讨论】:

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


    【解决方案1】:

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

    您需要在 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();
    }
    

    【讨论】:

      【解决方案2】:

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

      例如

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-10
        • 1970-01-01
        • 2019-06-29
        • 2013-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多