首页 >后端开发 >C++ >如何查明未处理异常的确切来源?

如何查明未处理异常的确切来源?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-11-14 11:30:02434浏览

How to Pinpoint the Exact Source of Unhandled Exceptions?

识别未处理异常的确切来源

通常需要确定导致异常的特定代码行,即使它不是由程序员显式生成的。

自定义异常类和宏

推荐的方法包括创建自定义异常类和相应的宏。例如:

class my_exception : public std::runtime_error {
    std::string msg;
public:
    my_exception(const std::string &arg, const char *file, int line) :
    std::runtime_error(arg) {
        std::ostringstream o;
        o << file << ":" << line << ": " << arg;
        msg = o.str();
    }
    ~my_exception() throw() {}
    const char *what() const throw() {
        return msg.c_str();
    }
};
#define throw_line(arg) throw my_exception(arg, __FILE__, __LINE__);

用法:

my_exception 类构造自定义异常消息,其中包括文件名、行号和用户定义的错误消息。 throw_line 宏用于生成带有这些增强的错误消息的自定义异常。

在以下示例中,在函数 f 中使用 throw_line 宏:

void f() {
    throw_line("Oh no!");
}

当 f 抛出异常时, main 函数捕获它并将自定义的错误消息打印到控制台:

int main() {
    try {
        f();
    }
    catch (const std::runtime_error &amp;ex) {
        std::cout << ex.what() << std::endl;
    }
}

这种方法提供了一种方便的机制,用于生成异常及其来源的详细信息,无论它们是否是显式生成的。

以上是如何查明未处理异常的确切来源?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn