c++ - 抛出异常错误 'terminate called...'

标签 c++

好的,所以我一直在关注 C++ 指南,并且最近进入了有关异常处理的部分。 我无法使我的任何代码正常工作 - 它们都对以下错误产生了一些变化;

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

其中“char const*”是我抛出的任何类型。

我按 ctrl-c、ctrl-v 编辑了指南中的示例代码,然后运行它以查看该错误是我的错,还是其他原因。它产生了与我的代码相同的错误(上图)。

这是指南中的代码;

#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;
    }
}

最佳答案

始终捕获绝对 const 异常:catch (const char const* strException)
对它们进行更改(写操作)既无意也无用。甚至在可能的堆栈本地拷贝上也不行。

尽管您所做的似乎不是一个好主意。异常的约定是这些应该实现一个 std::exception 接口(interface),它们可以以规范的方式被捕获。符合标准的方式是

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);
}

关于c++ - 抛出异常错误 'terminate called...',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24458563/

相关文章:

c++ - 当同一个库动态和静态链接到 C++ 程序时会发生什么?

c++ - 生命周期短的分配会导致堆碎片吗?

c++ - 内存泄漏: When do they happen?

c++ - 在模板中实例化模板对象

c++ - 使用动态插件处理 Qt5 中的 QMetaType 注册

c++ - 如何清理坏的 OpenSSL 连接

c++ - Qt : element visible and not obscured (no need to scroll)

c++ - enable_if 用于没有返回类型的函数

c++ - 以编程方式从函数名称获取序数

c++ - 从栈 move 到堆