Can a function marked as noexcept have exceptions inside?

你。 提交于 2019-12-10 18:23:52

问题


Let's say that I have a function marked as noexcept but there's a line of code inside that can throw. That line of code will be in a try block and the exception will be caught. Does that cause anything?

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

回答1:


Yes, this is perfectly legal, as long as the exception doesn't leak out of the function.

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.

[except.spec/11 in C++11]




回答2:


Searching for an exception handler is done from the inside out, searching one level less deep whenever nothing is found to handle the exception.

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. ]

The only time noexcept(true) has a visible effect is if an exception is thrown from inside the function, and no matching handler is present. No special effect is specified for an an exception with a matching handler, so that must run the same as in a noexcept(false) function.



来源:https://stackoverflow.com/questions/28974999/can-a-function-marked-as-noexcept-have-exceptions-inside

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!