C++ 异常 - 将 c-string 作为异常抛出是不是很糟糕?

我正在开发一个小型 c++ 程序并学习异常。下面的代码是否“不好”,如果是,我可以做些什么来改进它?

try {
    // code
    if (some error) {
        throw "Description of error.";
    }
}
catch (char* errorMessage) {
    cerr << errorMessage << endl << "Fatal error";
}

char 数组作为异常抛出有什么问题吗?

编辑: 这会是更好的方法吗?

const char errorMessage[] = "Description of error";

try {
    // code
    if (some error) {
        throw errorMessage;
    }
}
catch (char* errorMessage) {
   cerr << errorMessage << endl << "Fatal error";
}

最佳答案

抛出一个标准的异常对象要好得多。一般来说,最好的做法是抛出一些从 std::exception 派生的东西,这样如果在某些情况下它确实导致你的程序终止,实现就有更好的机会打印有用的诊断信息。

因为这样做并不难,所以我绝不建议抛出原始字符串文字。

#include <stdexcept>

void someFunction()
{
    try {
        // code
        if (some error) {
            throw std::runtime_error( "Description of error." );
        }
    }
    catch (const std::exception& ex) {
        std::cerr << ex.what() << "\nFatal error" << std::endl;
    }
}

https://stackoverflow.com/questions/6248404/

相关文章:

c++ - 计算机如何进行浮点运算?

c++ - 如何在编译时检查结构的大小?

c++ - 我收到错误 "invalid use of incomplete type ' 类映射'

c++ - C 和 C++ 中的 1LL 或 2LL 是什么?

c++ - 为什么 std::fstream 类不采用 std::string?

c++ - std::pair 的顺序是否明确?

c++ - VS2012 在 64 位目标中 vector 的性能不佳

c++ - 如何强制 gcc 链接未使用的静态库

c++ - 访问另一个子类中基类的 protected 成员

c++ - std::map 如何提供常量 size() 操作?