标记为 noexcept 的函数内部可以有异常吗?

Can a function marked as noexcept have exceptions inside?

假设我有一个标记为 noexcept 的函数,但其​​中有一行代码可以抛出异常。该行代码将位于 try 块中,异常将被捕获。这会导致什么吗?

void MyFunc() noexcept
{
    try {
        throw std::exception("...");
    } catch (const std::exception & e) {
        // I'll deal with it here...
    }
}

是的,这是完全合法的,只要异常不会从函数中泄漏出来。

An implementation shall not reject an expression merely because when executed it throws or might throw an exception that the containing function does not allow.

[除了 C++11 中的spec/11]

异常处理程序的搜索是从内到外完成的,当找不到任何异常处理程序时,搜索的深度会降低一层。

15.3 Handling an exception [except.handle]

4 The handlers for a try block are tried in order of appearance. [...]

[...]

6 If no match is found among the handlers for a try block, the search for a matching handler continues in a dynamically surrounding try block of the same thread.

15.4 Exception specifications [except.spec]

9 Whenever an exception is thrown and the search for a handler (15.3) encounters the outermost block of a function with an exception-specification that does not allow the exception, then,

[... std::unexpected() or std::terminate() is called. ]

唯一一次 noexcept(true) 具有可见效果的情况是从函数内部抛出异常,并且不存在匹配的处理程序。没有为具有匹配处理程序的异常指定特殊效果,因此必须 运行 与 noexcept(false) 函数中的相同。