如何将有关最顶层调用/上下文的信息添加到异常中

时间:2012-12-03 11:25:49

标签: c++ exception error-handling

我想补充一下该程序将要对我做什么的信息 异常处理。旧代码有一个很大的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_exceptionoperation1_exceptionoperation2_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");
  }
}

因此我有一个问题:显示附加内容的好模式是什么 发生错误时程序正在做什么的信息。

1 个答案:

答案 0 :(得分:0)

看看POCO(c ++库)投掷系统,它应该回答你所有的问题,你将从中学到很多很多好的风格规则。不幸的是,对你的问题的反感很长(至少我不知道如何缩短它)。

无论如何不要实现使你的代码不可读的东西,在你的示例代码中是不可读的,然后是不可维护的。