我想在我的异常处理中添加有关程序将要做什么的信息。旧代码对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
-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
可能会抛出,我捕获它的异常并将其转换为 a
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");
}
}
因此我有一个问题:什么是一个好的模式来显示错误发生时程序正在做什么的附加信息。