What is the meaning of `void func () throw (type)`?

I know this is a valid C ++ program. What is the meaning of a throw in a function declaration? AFAIK does nothing and is not used for anything.

#include <exception>
void func() throw(std::exception) { }
int main() { return 0; }
+3
source share
6 answers

This is an exception specification, and it is almost certainly a bad idea .

It states what it funccan std::exceptionthrow, and any other exception that throws funcwill result in a call unexpected().

+12
source

, std::exception func(), . - , unexpected(), terminate().

, , , - , , . , try{...}catch(){...} func(), .

, Guru of the Week. , throws() - , .

+17

++. , std::exception.

, ++ , . , , ( Java).

,

+2

. , , func(), std:: exception ( ). std:: .

0

. (), throw, , , , , . . 15.4 .

. . throw() .

0

:

void func() throw(std::exception,B) {  /* Do Stuff */}

:

void func()
{
    try
    {
        /* Do Stuff */ 
    }
    catch(std::exception const& e)
    {
        throw;
    }
    catch(B const& e)
    {
        throw;
    }
    catch(...)
    {
        unexpected();  // This calls terminate
                       // i.e. It never returns.
    }
}

terminate() , , RAII . , , , ( ).

(imho) , , - swap(). no-throw, swap() no-throw.

void myNoThrowFunc() throws()  // No-Throw (Mainlly for doc purposes).
{
    try
    {
        /* Do Stuff */
    }
    catch(...)  // Make sure it does not throw.
    {
        /* Log and/or do cleanup */
    }
}
0

Source: https://habr.com/ru/post/1720474/


All Articles