gpt4 book ai didi

c++ - 如何自定义未捕获的异常终止行为?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:15:36 25 4
gpt4 key购买 nike

g++clang++ 中(至少在 Linux 中)在抛出异常但未捕获异常(未捕获的异常)后显示以下典型消息:

terminate called after throwing an instance of 'std::runtime_error'
what(): Bye

例如:

#include<stdexcept>
int main(){
throw std::runtime_error("Bye");
}

如何自定义错误消息,同时仍然可以完全访问抛出的异常?

文档 ( http://www.cplusplus.com/reference/exception/set_unexpected/ ) 提到了 set_unexpected (和 set_terminate),但我不知道 unexpected_handle 是如何实际访问的抛出的异常,例如调用 e.what() 或其他东西。

注意:这背后的原因是我想为一个比简单的what() 包含更多信息的更复杂的异常类层次结构自定义消息,并且我希望在抛出此类异常时显示它(但如果抛出简单的 std::exception&,则默认值与典型值相同。

Note2:根据目前的两条建议,“通过捕获异常来自定义未捕获的异常”。将类似于代码中的内容。我想知道是否有一种方法可以在不向我编写的 all main() 代码添加 try-catch block 的情况下执行相同的操作。

#include<stdexcept>
int main() try{
....
}catch(std::exception& e){
std::clog << "terminate called after throwing an instance of '" << typeid(e) << "'\n"
<< " what(): " << e.what() << '\n'
<< "otherinfo, like current time\n";
}catch(alternative_exception& e){
std::clog << "terminate called after throwing an instance of '" << typeid(e) << "'\n"
<< " what(): " << e.what() << '\n'
<< " where(): " << e.where() << '\n'
<< " how(): " << e.how() << '\n'
<< "othermember(): " << e.othermember() << '\n';
}

最佳答案

除了实际捕获您关心的异常,std::set_terminate()std::current_exception() (C++11) 应该足以做一些有趣的事情。

关于c++ - 如何自定义未捕获的异常终止行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17258733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com