考虑以下代码片段:
struct ExceptionBase : virtual std::exception{};
struct SomeSpecificError : virtual ExceptionBase{};
struct SomeOtherError : virtual ExceptionBase{};
void MightThrow();
void HandleException();
void ReportError();
int main()
{
try
{
MightThrow();
}
catch( ... )
{
HandleException();
}
}
void MightThrow()
{
throw SomeSpecificError();
}
void HandleException()
{
try
{
throw;
}
catch( ExceptionBase const & )
{
// common error processing
}
try
{
throw;
}
catch( SomeSpecificError const & )
{
// specific error processing
}
catch( SomeOtherError const & )
{
// other error processing
}
ReportError();
}
void ReportError()
{
}
标准第 15.1.4 节告诉我们:
抛出异常的临时副本的内存是
除 3.7.3.1 中注明的情况外,以未指定的方式分配。这
只要有正在执行的处理程序,临时就会持续存在
那个例外。特别是,如果处理程序通过执行
扔;语句,将控制权传递给另一个相同的处理程序
例外,所以暂时保留。当最后一个处理程序被
通过 throw 以外的任何方式执行异常退出;这
临时对象被销毁并且实现可能会释放
临时对象的内存;任何此类释放都是在
一种未指定的方式。破坏发生后立即发生
销毁异常声明中声明的对象
处理程序。
我在查看处理程序时是否正确main
作为“最后的处理者?”因此,允许任意数量的重新抛出和捕获HandleException
不会导致当前异常对象的破坏?
我将 main 中的处理程序视为“最后一个处理程序”是否正确?
是的,你是。
因此,HandleException 中允许任意数量的重新抛出和捕获,而不会导致当前异常对象的销毁?
是的。最终未处理的异常对象将被编译器生成的代码销毁。不会造成内存泄漏。
重新扔进去也不好HandleException()
。反而
1. 将捕获写入任何请求特定处理的异常类型;
2.您可以使用以下方法对异常处理进行分组dynamic_cast
。捕获基本异常类型并尝试将其向下转换为其任何派生异常类。但dynamic_cast
这不是一个好的做法。所以最好使用第一种解决方案。
最好按以下方式重写代码:
struct ExceptionBase : virtual std::exception{};
struct SomeSpecificError : virtual ExceptionBase{};
struct SomeOtherError : virtual ExceptionBase{};
void MightThrow();
void HandleExceptionBase();
int main()
{
try
{
MightThrow();
}
catch (SomeOtherError &error) {
// first common code
HandleExceptionBase();
// react on this exception correctly
// specific code
}
catch (SomeSpecificError &error) {
// first common code
HandleExceptionBase();
// react on this exception correctly
// specific code
}
catch (ExceptionBase &error) {
HandleExceptionBase();
// finally catch anything derived from base class
// react on this exception correctly
}
catch(...) {
// react on any other exception except 3 listed above
}
}
void MightThrow()
{
throw SomeSpecificError();
}
void HandleExceptionBase() {
// base exception handler
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)