Gal*_*man 18 c++ nested exception
我可以嵌套try-catch块吗?例如:
void f()
{
try
{
//Some code
try
{
//Some code
}
catch(ExceptionA a)
{
//Some specific exception handling
}
//Some code
}
catch(...)
{
//Some exception handling
}
}//f
Run Code Online (Sandbox Code Playgroud)
Pat*_*ien 11
如前所述,这是可能的,但你必须看到这种"落地"计划.如果在第一个try-catch-block中捕获了异常,它将不会被外部catch块捕获.但是,如果它没有被内部catch块捕获,它将尝试在外部catch块中找到匹配的异常处理程序.
您还可以通过throw;在内部异常处理程序中使用,明确地将异常提升到下一个异常处理程序.
例如这段代码:
try
{
try
{
throw std::runtime_error("Test");
}
catch (std::runtime_error& e)
{
std::cerr << "Inner Exception-Handler: " << e.what() << std::endl;
throw;
}
}
catch (std::exception& e)
{
std::cerr << "Outer Exception-Handler: " << e.what() << std::endl;
}Run Code Online (Sandbox Code Playgroud)
将导致:
Inner Exception-Handler: Test Outer Exception-Handler: Test
这是有效的,因为std :: runtime_error是从std :: exception派生的.您还应该注意到,在这样一个简单的示例中,也可以在彼此之后编写catch块,但是如果要在第一个catch块之后执行其他代码,则必须嵌套它们.
是的,那是合法的.正如ouster所说,处理它的一种方法是将内部try-catch块放在它自己的函数中,并从你的外部try-catch块调用该函数.
处理它的另一种方法是使用多个catch块.
void f()
{
try
{
//Some code that throws ExceptionA
//Some code that throws ExceptionB
}
catch(ExceptionA ea)
{
//Some exception handling
}
catch(ExceptionB eb)
{
//Some exception handling
}
}//f
Run Code Online (Sandbox Code Playgroud)
这里需要注意的是catch块中异常类型的特殊性.如果ExceptionB在上面的示例中扩展了ExceptionA,则永远不会调用ExceptionB块,因为任何抛出的ExceptionB都将由ExceptionA块处理.在处理Exception类层次结构时,您必须以最特定到最不具体的顺序对catch块进行排序.
| 归档时间: |
|
| 查看次数: |
18206 次 |
| 最近记录: |