5

我的程序如下:(在linux上)

// Ex. 2 of Exception Handling
// Here divn() raises the exception but main() will be the exception handler

#include<iostream>
using namespace std;

int divn(int n, int d)
{
    if(d == 0)
        throw "Division by ZERO not possible ";

    return n/d;
}

main()
{
    int numer, denom;
    cout << "Enter the numerator and denominator : ";
    cin >> numer >> denom;
    try
    {
        cout << numer << " / " << denom << " = " << divn(numer,denom) << endl;
    }
    catch(char *msg)
    {
        cout << msg;
    }
    cout << "\nEnd of main() \n ";
}

/*当我们将分母设为0时,它应该抛出异常并提供给定的错误消息。当我输入分母为0时得到的输出如下:

管理员@ubuntu:~/FYMCA/CPP_class$ g++ prog110.cpp administrator@ubuntu:~/FYMCA/CPP_class$ ./a.out 输入分子和分母: 12 0 在抛出 'char const*' 实例后终止调用已中止(核心转储)

我该如何解决这个问题?

4

4 回答 4

11

字符串文字有 type char const[],衰减到char const*. 您应该catch相应地调整您的处理程序:

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

这是一个活生生的例子

最后,这是一种更好的重写程序的方法,使用 C++ 标准库中的异常类:

#include <iostream>
#include <stdexcept>
//       ^^^^^^^^^^^ For std::logic_error

int divn(int n, int d)
{
    if(d == 0)
    {
        throw std::logic_error("Division by ZERO not possible ");
        //    ^^^^^^^^^^^^^^^^
        //    Throw by value
    }

    return n/d;
}

int main() // <== You should specify the return type of main()!
{
    // Rather use these than "using namespace std;"
    using std::cout;
    using std::cin;
    using std::endl;

    int numer, denom;
    cout << "Enter the numerator and denominator : ";
    cin >> numer >> denom;

    try
    {
        cout << numer << " / " << denom << " = " << divn(numer,denom) << endl;
    }
    catch(std::logic_error const& err)
    //    ^^^^^^^^^^^^^^^^^^^^^^^
    //    Catch by reference
    {
        cout << err.what();
        //      ^^^^^^^^^^
    }

    cout << "\nEnd of main() \n ";
}

当然还有相应的活生生的例子

于 2013-04-03T17:54:42.887 回答
2

异常消息有点说,你抓错了类型。

于 2013-04-03T17:54:50.677 回答
1

您不应该以这种方式抛出异常。一个好的做法是在 stdexcept 库中使用标准异常,例如 std::runtime_error 或 std::logic 错误,或者基于 std::exception 创建自己的异常类

于 2013-04-03T17:54:25.640 回答
-1

一个简单的解决方法是在顶部添加一条语句,如下所示:

char * err = "Division by ZERO not possible";

然后,将您的更改throwthrow err;

它与编译器如何为字符串文字分配存储空间有关。

于 2013-04-03T17:59:35.800 回答