问题
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()
orstd::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