【发布时间】:2012-11-20 20:36:46
【问题描述】:
我想添加有关该程序将要做什么的信息到我的
异常处理。旧代码在所有内容周围都有一个大的try-block:
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-block 转换为三个block,但这感觉很奇怪:
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");
}
}
因此我有一个问题:什么是显示附加信息的好模式? 发生错误时程序正在做什么的信息。
【问题讨论】:
-
我想你正在寻找这样的东西:stackoverflow.com/a/4284039/476681
标签: c++ exception error-handling