c++ - 如何知道导致异常的确切代码行?

标签 c++ exception

如果我自己生成异常,我可以在异常中包含任何信息:代码行数和源文件的名称。像这样的:

throw std::exception("myFile.cpp:255");

但是未处理的异常或不是我生成的异常是怎么回事?

最佳答案

更好的解决方案是使用自定义类和宏。 :-)

#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>

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

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

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

关于c++ - 如何知道导致异常的确切代码行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/348833/

相关文章:

c# - 哪个更利于可读性?

C# 显示 Oracle 过程中的自定义错误

exception - 异常会自动传播吗?

c++ - 使用 boost::filesystem 时如何正确处理错误?

C++ - 保存和删除

c++ - 在 C++ 中禁用自动 DLL 加载

java - 未报告的异常NegativeNumber;必须被捕获或宣布被扔出

c# - Web API Controller 中的异常处理并抛出自定义错误消息

c++ - 具有来自同一个 bool C++ 的两个 if 语句的最佳实践

c++ - 我该如何解决CUDA编程中的 fatal error C1070:文件中的#if/#endif对不匹配?