C++ Do I need to write throw clause for a function

2019-05-07 12:53发布

Before

Consider to have a class and a global function:

This is, for example, usefulfuncts.hpp

void dosome(int a, int b) throw (std::exception);

This is usefulfuncts.cpp

void dosome(int a, int b) throw (std::exception) {
   //...
}

And this is aclass.hpp

class aclass {
   // Members...
   friend void dosome(int a, int b) throw (std::exception);
   // Members...
};

After (what I would like that to be)

Ok! I would like to understand if it is strictly necessary to write everytime the throw clause. So for example can I do this?

This is usefulfuncts.hpp

void dosome(int a, int b) throw (std::exception);

This is usefulfuncts.cpp

void dosome(int a, int b) { /* OMITTING IT! */
   //...
}

And this is aclass.hpp

class aclass {
   // Members...
   friend void dosome(int a, int b); /* OMITTING IT */
   // Members...
};

Is this right? To put it only in the main declaration? Thanks

3条回答
放荡不羁爱自由
2楼-- · 2019-05-07 13:12

Exception specifications are deprecated in C++11 - do not write exception specifications unless it is to specify that your function is guaranteed not to throw an exception.

Note that actually providing this guarantee is harder than it may seem - Herb Sutter has written many articles and a book on the subject of exceptions and exception safety.

查看更多
我只想做你的唯一
3楼-- · 2019-05-07 13:17

Declaring exceptions is a bad idea. From http://www.gotw.ca/publications/mill22.htm :

Moral #1: Never write an exception specification.
Moral #2: Except possibly an empty one, but if I were you I’d avoid even that.

查看更多
走好不送
4楼-- · 2019-05-07 13:20

Omitting a exception specification means that your function can throw any exception.

Exceptions specifications are bad. There are hardly any compilers which implement the feature correctly. They have been deprecated since the C++11 Standard. In fact Exception specifications were considered a failed experiment even while they were a part of the C++03 standard.

Good Read:
A Pragmatic Look at Exception Specifications

查看更多
登录 后发表回答