开发者

C++: Indicating a function may throw [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Is there a generally accepted idiom for indicating C++ code can throw exceptions?

How do you indicate in your code when a C++ function is possible to throw something? I don't mean through documentation, but through开发者_Python百科 syntax.

For example I tried placing a throw(std::exception) at the end of the function declaration, but that gave me a warning saying that "C++ exception specification ignored except to indicate a function is not __declspec(nothrow)", which I guess means the compiler ignored the throw and proceeded as if it were not there.

I also tried adding a throw() (without anything in the parenthesis) at the end of the declaration, but — contrary to my expectations — that means the function is expected to never throw anything: "function assumed not to throw an exception but does".

Atm I'm using throw(...) to syntactically indicate the function may throw as this doesn't give me any errors or warnings. Do you have any other suggestions as to how I might indicate this through syntax?


You don't. Exception specifiers do not mean "Here's what I can throw", they mean "if anything other than this gets thrown, go to std::terminate". This behavior is counterintuitive to the point that MSVC++ does not and will not support them.

The semantics of C++ is that you must assume a function can always throw.


Most of the compilers are non conforming to the standard when it comes to Exception specifications. Exceptions specifications are considered as an experiment that failed.
For example:
If you have a blank exception specification then what gets called? the unexpected() method or a bad_exception will be thrown and if both in what order?

 #include "stdafx.h"  
 #include <stdio.h>  
 #include <exception>  
 #include <iostream>  


using namespace std;

class A
{
    public:
        int i;
};

void myunexpected () 
{
    cerr << "unexpected called\n";
}

void doSomething(void) throw();
void doSomething(void) throw()
{
    A obj;
    obj.i= 100;
    throw obj;
}


int _tmain(int argc, _TCHAR* argv[])
{
    set_unexpected (myunexpected);
    try 
    {
        doSomething();
    }
    catch (bad_exception be) 
    {
        puts("Caught something");
    }
    catch (A &obj) 
    {
        puts("Caught Integer");
    }
    return 0;
}

If you run this code on Visual studio, you will see that the exception just gets caught by the appropriate handler.

So to conclude, Exception specifications is a failed experiment and it's best to avoid them.


Basically, throw specifiers are worthless, as was discovered after their introduction, unfortunately, and current compilers ignore them. They're deprecated, and quality libraries don't include them. Just don't bother with them. C++0x officially deprecates them, and only has a noexcept keyword.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜