I'm reading this book on C++ and there's a code example that should behave differently: it should throw an exception or error (sorry for the poor terminology here) anyway it just shouldn't work or so the book says. (the book is rather new so I think its up to date). But in my case the code executes itself and I get the "Exception caught" message.
The author uses a different compiler (WxDev). (I'm using Visual Studio 2019)
#include<exception>
void generate_char_exception() throw(int)
{
throw 'x';
}
int main()
{
try
{
generate_char_exception();
}
catch (...)
{
cout << "Exception caught" << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
对于初学者,throw()不建议使用规范,而是首选noexcept。我想知道您的书是如何更新的,无论如何,我建议您看一下这份C ++优秀书籍的清单:The Definitive C ++ Book Guide and List。要更深入地了解抛出规范及其原因,请访问http://www.gotw.ca/publications/mill22.htm(感谢user4581301)
现在,答案:
根据https://en.cppreference.com/w/cpp/language/except_spec
如果该函数抛出其异常规范中未列出的类型的异常,则调用函数std :: unexpected。默认函数调用std :: terminate,[...]
因此,这本书似乎是正确的,并且在使用g ++时,您会得到预期的行为:https : //onlinegdb.com/Sy_7DzUmB
terminate called after throwing an instance of 'char'
Aborted
Run Code Online (Sandbox Code Playgroud)
如果使用throw(char)异常会被捕获。
Microsoft Visual Studio 2019不实现这种异常规范:https : //docs.microsoft.com/zh-cn/cpp/error-messages/compiler-warnings/compiler-warning-level-3-c4290?view=vs -2019年
使用异常规范声明函数,Visual C ++接受该异常规范,但未实现。具有异常规范的代码在编译过程中被忽略,可能需要重新编译并链接以在支持异常规范的将来版本中重用。
并且来自:https : //docs.microsoft.com/zh-cn/cpp/cpp/exception-specifications-throw-cpp?view=vs-2019
throw(type):(C ++ 14和更早版本)该函数可以引发type异常type。编译器接受语法,但将其解释为 noexcept(false) [...]
有趣的是,这也是链接链接文章中Herb Sutter所说的
至少有一种流行的C ++编译器(Microsoft,最高为7.x版)会解析异常规范,但实际上并没有执行它们,从而将异常规范还原为美化的注释。
最后,此答案出于好奇,throw()已从最新版本的语言(https://en.cppreference.com/w/cpp/language/except_spec)以各种形式弃用(并删除) 。
首选noexcept:https : //en.cppreference.com/w/cpp/language/noexcept_spec
| 归档时间: |
|
| 查看次数: |
115 次 |
| 最近记录: |