[英]Is logging in an exception constructor bad practice?
1.) What kind of exception logging is the better practice? 1.)更好的做法是哪种异常日志记录?
//1 xor //2
2.) Is this question language specific? 2.)此问题语言是否特定? (Most interested in c++)
(对c ++最感兴趣)
To the code: 到代码:
:: LOG is macro for singleton-logger :: LOG是单例记录器的宏
struct myExc : virtual std::runtime_error
{
myExc( std::string const&msg )
:runtime_error(msg)
{
LOG << msg; //1
}
};
void foo_throw()
{
throw myExc("");
}
/// some_where
...
try()
{
foo_throw();
}
catch( myExc const& e)
{
LOG << e.what(); //2
}
catch(...
The second variant is preferable, because some code further up the call stack could choose to catch the exception without outputting an error. 第二个变体是可取的,因为调用堆栈后面的某些代码可以选择捕获异常而不输出错误。 In the first version, you output as soon as the exception is created, thus giving catching code less choice.
在第一个版本中,您将在创建异常后立即输出,从而使捕获代码的选择更少。
For example, you might do something like this: 例如,您可以执行以下操作:
try
{
foo_throw();
}
catch (myExc& e)
{
//do some recovery
}
If your exception constructor outputs something, you can't do anything about it when catching said exception. 如果您的异常构造函数输出某些内容,则在捕获该异常时您将无能为力。
The first one is probably 'too smart'. 第一个可能是“太聪明了”。 And do you sure about that the
LOG <<
cannot throw exception? 并且您确定
LOG <<
不会引发异常吗? In second case you have more information and more possibilities to consider what happen if LOG <<
throws, especially you can do obligatory safe stuff before log. 在第二种情况下,您有更多的信息和更多的可能性来考虑如果
LOG <<
抛出,该怎么办,尤其是您可以在日志记录前做必要的安全操作。
And first case tried to does two things: inform about exception and log message. 第一种情况试图做两件事:告知异常和日志消息。 This is bad.
这不好。 In second case you only inform about exception and after that you handle it: do stuff and log.
在第二种情况下,您仅会通知有关异常的信息,然后再处理:处理并记录。
Second case is example of separation of responsibility where one class does one task. 第二种情况是责任分离的示例,其中一个班级完成一项任务。
Also yours exception class is free from dependency of logger which is also good stuff. 另外,您的异常类不受记录器的依赖,这也是一件好事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.