Catch处理程序没有执行

时间:2012-06-17 06:48:57

标签: c++ exception-handling try-catch

我有以下代码。

#include "math.h" // for sqrt() function
#include <iostream>
using namespace std;

int main()
{
    cout << "Enter a number: ";
    double dX;
    cin >> dX;

    try // Look for exceptions that occur within try block and route to attached catch block(s)
    {
        // If the user entered a negative number, this is an error condition
        if (dX < 0.0)
            throw "Can not take sqrt of negative number"; // throw exception of type char*

        // Otherwise, print the answer
        cout << "The sqrt of " << dX << " is " << sqrt(dX) << endl;
    }
    catch (char* strException) // catch exceptions of type char*
    {
        cerr << "Error: " << strException << endl;
    }
}

运行程序后,我输入一个负数,并期望catch处理程序执行并输出Error: Can not take sqrt of negative number。相反,程序以以下消息终止

Enter a number : -9
terminate called after throwing an instance of 'char const*'
Aborted

为什么我的异常没有在catch处理程序中捕获?

2 个答案:

答案 0 :(得分:2)

你必须添加const:

catch (char const * strException) // catch exceptions of type char*

实际上你正在抛出char const *,但期望变异char *,这种方式不匹配(反之亦然)。

答案 1 :(得分:1)

为什么你要扔掉和捕捉字符串呢?

你应该抛出并捕获异常。

始终记住遵循拇指规则

每当在代码中的引号中插入一个字符串时,它都会返回一个以null结尾的const char