Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to signify to the compiler that a function always throws? [duplicate]

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.

like image 932
Assaf Lavie Avatar asked Jun 28 '09 07:06

Assaf Lavie


People also ask

How do we tell the compiler that a certain function will not throw exceptions?

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.

What happens if a noexcept function throws?

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.

What is throw() in C++?

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.

Does throw exit the function C++?

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


2 Answers

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";
}
like image 200
Andrew Tomazos Avatar answered Nov 12 '22 20:11

Andrew Tomazos


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.

like image 32
Jesse Hall Avatar answered Nov 12 '22 20:11

Jesse Hall