如何将有关最顶层调用/上下文的信息添加到异常
How to add information about the topmost call/context to an exception
我想添加有关程序将要对我的异常处理。旧代码在所有内容周围都有一个大try
块:
try {
read_cfg(); // a sub call might throw runtime_error
operation1();
operation2();
}
catch (std::exception& e) {
std::cerr
<< "Error: " << e.what() << ", "
// FIXME: also show what we were trying to do
// FIXME: and what a user could try
<< "n";
}
错误消息示例:
Error: file "foo.cfg" not found, while reading configuration.
Please make sure the file exists.
我将try
块转换为三个块,但这感觉很奇怪:
try {
read_cfg(); // a sub call might throw runtime_error
}
catch (std::exception& e) {
std::cerr
<< "Error: " << e.what() << ", "
<< "while reading configuration."
<< "n";
}
try {
operation1();
}
catch (std::exception& e) {
std::cerr
<< "Error: " << e.what() << ", "
<< "while performing operation 1."
<< "n";
}
try {
operation2();
}
catch (std::exception& e) {
std::cerr
<< "Error: " << e.what() << ", "
<< "while performing operation 2."
<< "n";
}
我还尝试在每次调用中引入一个异常类(read_cfg_exception
, operation1_exception
,operation2_exception
)。由于在 read_cfg() 中调用 open
可能会抛出,我捕获了它的异常并将其转换为 read_cfg_exception
,从而保存附加信息,即某些东西当"读取配置时"出错时。然而,这感觉也不对:
class read_cfg_exception;
void open(std::string name); // might throw std::runtime_error
void read_cfg()
{
try {
open("foo.cfg");
}
catch (std::runtime_error& e) {
throw read_cfg_exception(e.what() + "while reading configuration");
}
}
因此,我有一个问题:显示附加的好模式是什么发生错误时程序正在执行的操作的信息。
看看
POCO(c ++库)抛掷系统,它应该可以回答你所有的问题,你会从中学到很多东西,也有很多好的风格规则。不幸的是,你的问题会很长(至少我不知道如何让它简短)。
无论如何,不要实现使代码不可读的东西,在您的示例中代码不可读,然后不需要维护。
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- #为""定义宏;静态";针对不同的上下文
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 与互斥锁相比,旋转锁可以保证上下文切换
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 为什么我不能使用 EGL 创建无头 OpenGl 上下文?
- 如何设置一个范围来提取我想要获得的信息
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- 错误"Could not find Boost"(缺少:上下文标头)
- 超载功能没有上下文类型信息
- 如何将有关最顶层调用/上下文的信息添加到异常
- 如何在使用 OpenCL 时指定上下文(平台/设备信息)
- 如何将上下文信息传递给自定义运算符<<适用于 std::iostream
- 如何在不同的上下文(例如线程)中保留原始异常类型信息
- 在谈论重叠 I/O 时,上下文信息是什么意思
- 没有上下文类型信息的重载函数 |无法根据转换为类型 'int' 解析重载函数'swap'
- 类声明错误:上下文信息不足,无法确定类型
- 上下文信息不足,无法确定类型