我正在使用Linux上的gcc编译C++代码。有一些异常情况不应该被处理,而应该关闭程序。但是,我想要能够显示异常字符串:
例如:
throw std::runtime_error(" message");
不会显示消息,只显示错误类型。我也想显示消息。有没有办法做到这一点?
这是一个库,我真的不想放置catch语句并让库用户决定。然而,现在库用户是Fortran,它不允许处理异常。原则上,我可以在包装器代码中放置处理程序,但如果有其他方法的话,我宁愿不这样做。
标准异常有一个虚拟的what()
方法,它提供与异常相关联的消息:
int main() {
try {
// your stuff
}
catch( const std::exception & ex ) {
cerr << ex.what() << endl;
}
}
try{
}catch(const std::exception &e){
std::cerr << e.what() << std::endl;
throw;
}
try/catch
块和 throw;
语句来让库用户处理异常。 throw;
语句将控制权转移给同一异常的另一个处理程序。GCC自6.2.0版本起就会显示此信息。
我曾在g++ 6.2.0、Ubuntu 16.10上测试过它,现在又在g++ 9.3.0 Ubuntu 20.04上进行了测试,两者都显示了这个消息,不确定行为什么时候发生了改变:
#include <stdexcept>
void myfunc() {
throw std::runtime_error("my message");
}
int main() {
myfunc();
}
编译并运行:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
输出包含my message
错误信息:
terminate called after throwing an instance of 'std::runtime_error'
what(): my message
throw std::runtime_error(" message");
会显示消息。 - Ciro Santilli OurBigBook.com