When calling functions that always throw from a function returning a value, the compiler often warns that not all control paths return a value. Legitimately so.
void AlwaysThrows() { throw "something"; }
bool foo()
{
if (cond)
AlwaysThrows();
else
return true; // Warning C4715 here
}
Is there a way to tell the compiler that AlwaysThrows does what it says?
I'm aware that I can add another throw
after the function call:
{ AlwaysThrows(); throw "dummy"; }
And I'm aware that I can disable the warning explicitly. But I was wondering if there is a more elegant solution.
You can specify that a function may or may not exit by an exception by using an exception specification. The compiler can use this information to optimize calls to the function, and to terminate the program if an unexpected exception escapes the function. The function does not throw an exception.
Note that noexcept doesn't actually prevent the function from throwing exceptions or calling other functions that are potentially throwing. Rather, when an exception is thrown, if an exception exits a noexcept function, std::terminate will be called.
The throw keyword throws an exception when a problem is detected, which lets us create a custom error. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
throw usually causes the function to terminate immediately, so you even if you do put any code after it (inside the same block), it won't execute. This goes for both C++ and C#.
Use the noreturn
attribute. This is specified in section "7.6.3 Noreturn attribute [dcl.attr.noreturn]" of the latest version of the C++ standard third edition ISO/IEC 14882:2011.
Example from the standard:
[[ noreturn ]] void f()
{
throw "error";
}
You could add a dummy return statement after the call to AlwaysThrows(), with a comment explaining why it's there. This is also useful when the function you're calling always exit()s or abort()s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With