Passing an exception through a noexcept
function is supposed to terminate the program. My question is whether it is safe and reasonable practice to rely on this behavior in cases where you could have a program bug that leads the exception to be thrown.
A simple example would be when you want to call the same functions on both validated and unvalidated input, as in here:
#include <stdexcept>
struct tree {};
tree
parse(char *p)
{
if (*p)
throw std::length_error("only 0-length arguments allowed");
return {};
}
struct validated {
char *buf_;
validated(char *buf) : buf_(buf) { parse(buf_); }
};
tree
parse(const validated &v) noexcept
{
return parse(v.buf_);
}
In the above code, I would like parse(const validated &v)
to be noexcept
. Of course, there could be a bug in the code where I modify a buffer after it has already been validated. In that case I would like the program to crash and dump core like an assertion failure, but I want to avoid the risk of undefined or otherwise exploitable behavior that could do worse than crash the program.
Yes, it is safe from a C++ language standpoint. In the sense that it has well-defined, deterministic behavior.