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