引发异常错误"终止调用..."

Throwing exceptions error 'terminate called...'

本文关键字:终止 调用 错误 异常      更新时间:2023-10-16

好的,我一直在遵循c++指南,最近我读到了异常处理部分。我无法让我的任何代码工作-它都产生了以下错误的一些变化;

terminate called after throwing an instance of 'char const*'

其中"char const*"将是我抛出的任何类型

我ctrl-c, ctrl-v 'ed指南中的示例代码,并运行它,看看错误是我的错误,还是有其他事情发生。它产生了与我的代码相同的错误(如上)。

下面是指南中的代码;

#include "math.h" // for sqrt() function
#include <iostream>
using namespace std;
// A modular square root function
double MySqrt(double dX)
{
    // 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*
    return sqrt(dX);
}
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)
    {
        cout << "The sqrt of " << dX << " is " << MySqrt(dX) << endl;
    }
    catch (char* strException) // catch exceptions of type char*
    {
        cerr << "Error: " << strException << endl;
    }
}

Always catch absolute const例外:catch (const char const* strException) .
对它们进行更改(写操作)既不是有意的,也没有用。

虽然你现在做的似乎不是个好主意。异常的约定是,这些异常应该实现一个std::exception接口,这样它们就可以以规范的方式被捕获。标准的兼容方式是

class invalid_sqrt_param : public std::exception {
public:
     virtual const char* what() const {
         return "Can not take sqrt of negative number";
     }
};

double MySqrt(double dX) {
    // If the user entered a negative number, this is an error condition
    if (dX < 0.0) { 
        // throw exception of type invalid_sqrt_param
        throw invalid_sqrt_param(); 
    }
    return sqrt(dX);
}

// Look for exceptions that occur within try block 
// and route to attached catch block(s)
try {
    cout << "The sqrt of " << dX << " is " << MySqrt(dX) << endl;
}
// catch exceptions of type 'const std::exception&'
catch (const std::exception& ex) {
    cerr << "Error: " << ex.what() << endl;
}

注意:
已经为传递给函数的无效参数设计了一个标准异常。或者,您可以简单地执行

double MySqrt(double dX) {
    // If the user entered a negative number, this is an error condition
    if (dX < 0.0) { 
        // throw exception of type invalid_sqrt_param
        throw std::invalid_argument("MySqrt: Can not take sqrt of negative number"); 
    }
    return sqrt(dX);
}

正如评论中提到的,你不是在捕捉const char*,而是char*

如果你把合适的行改为const char*,它将像这个例子一样工作。

你可以像这个例子一样添加一个catch(...)块,但我强烈建议不要这样做,因为它可能会掩盖你一开始没有考虑到的实际问题。

风格指出:

    你不应该在cpp中使用#include "math.h",而应该使用#include <cmath>
  • 你不应该在实际代码中使用using namespace std;(只是指出这一点,以防"教程"没有)
  • 这个教程很臭,也许你应该找另一个来源。
相关文章: