我如何确定 "nearest" 异常处理程序

How I can determine the "nearest" exception handler

来自[except.throw]/2

When an exception is thrown, control is transferred to the nearest handler with a matching type ([except.handle]); “nearest” means the handler for which the compound-statement or ctor-initializer following the try keyword was most recently entered by the thread of control and not yet exited.

首先,我真的不能正确理解这句话,也不能理解它在特定代码中的应用。所以任何可以理解的解释,用简单的文字,将不胜感激。

考虑以下两个代码片段:

/ * code A */

try
{
  throw 1;
}
catch (int) // nearest handler for throwing 1. #first_handler
{
}

-----------------------------------------------

/* code B */

try
{
  try
  {
    throw 1;
  }
  catch (int) // nearest handler for throwing 1. #second_handler
  {
    throw 2;
  }
}
catch (int) // nearest handler for throwing 2
{
} 

因为我无法理解上面的引用,所以我不知道如何确定最近的处理程序,并且我无法在上面的示例中应用 [except.throw]/2。我的问题是如何在上面的代码中应用 [except.throw]/2 ?或者换句话说,为什么 first_handlersecond_handler 是最近的处理程序?

异常向上传播,因此您可以查找下一个 try 然后查看它是否有匹配的 catch,如果没有则继续。例如

try {                                  // 4
    try {                              // 2
        throw "foo";                   // 1
    } catch(int) { }                   // 3
} catch(...) {                         // 5
    std::cout << "hello exception";
}

当在 1 中抛出异常时,控制流向后退,第一个 try2 中的那个。它没有匹配的 catch,它只捕获 int (3)。因此,您进一步向上看,在 4 中找到 try。它有一个 catch 可以捕获任何异常 5 并且这是“最近的”。


[...] "“nearest” means the handler for which the compound-statement following the try keyword was most recently entered by the thread of control and not yet exited." What that's "not yet exited"? I can't get the bold part.

这是第二个例子:

try            // try 2
{
  try          // try 1
  {
    throw 1;
  }            // <---- the try block is exited here
  catch (int)  // catch 1
  {
    throw 2;
  }
}
catch (int)    // catch 2
{
} 

throw 2 将由 catch 2 处理,因为那是最近的处理程序。最近的处理程序不是 catch 1,因为它属于 try 1。当 throw 2 被执行时, try 1 块已经退出。