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

How to add information about the topmost call/context to an exception

本文关键字:上下文 信息 添加 异常 调用      更新时间:2023-10-16

我想添加有关程序将要对我的异常处理。旧代码在所有内容周围都有一个大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");
  }
}

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

看看

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

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