简体   繁体   English

C ++我是否需要为函数编写throw子句?

[英]C++ Do I need to write throw clause for a function everywhere?

Before 之前

Consider to have a class and a global function: 考虑拥有一个类和一个全局函数:

This is, for example, usefulfuncts.hpp 例如,这就是usefulfuncts.hpp

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

This is usefulfuncts.cpp 这是usefulfuncts.cpp

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

And this is aclass.hpp 这是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. 我想了解是否必须每次写入throw子句。 So for example can I do this? 那么我可以这样做吗?

This is usefulfuncts.hpp 这很有用usefulfuncts.hpp

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

This is usefulfuncts.cpp 这是usefulfuncts.cpp

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

And this is aclass.hpp 这是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 谢谢

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. 自C ++ 11标准以来,它们已被弃用。 In fact Exception specifications were considered a failed experiment even while they were a part of the C++03 standard. 实际上,Exception规范被认为是一个失败的实验,即使它们是C ++ 03标准的一部分。

Good Read: 好读:
A Pragmatic Look at Exception Specifications 务实看待例外规范

Declaring exceptions is a bad idea. 声明异常是一个坏主意。 From http://www.gotw.ca/publications/mill22.htm : 来自http://www.gotw.ca/publications/mill22.htm

Moral #1: Never write an exception specification. 道德#1:永远不要写异常规范。
Moral #2: Except possibly an empty one, but if I were you I'd avoid even that. 道德#2:除了可能是一个空洞的,但如果我是你,我甚至会避免。

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. 在C ++ 11中不推荐使用异常规范 - 除非要指定保证函数不会引发异常,否则不要编写异常规范。

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. 请注意,实际提供此保证比看起来更难--Herb Sutter撰写了许多关于例外和异常安全主题的文章书籍

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM