【问题标题】:How to add information about the topmost call/context to an exception如何将有关最顶层调用/上下文的信息添加到异常
【发布时间】: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_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");
  }
}

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

【问题讨论】:

标签: c++ exception error-handling


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-04-03
    • 2013-05-09
    • 2013-10-09
    • 2011-12-22
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    相关资源
    最近更新 更多