gpt4 book ai didi

c++ - 未处理的异常得到处理(visual studio 2019 这么聪明还是我遗漏了什么?)

转载 作者:太空狗 更新时间:2023-10-29 20:08:08 26 4
gpt4 key购买 nike

我正在阅读这本关于 C++ 的书,并且有一个代码示例应该有不同的行为:它应该抛出异常或错误(抱歉这里的术语很糟糕)无论如何它不应该工作或者书上说的那样。 (这本书很新,所以我认为它是最新的)。但在我的例子中,代码会自行执行,并且我收到“异常捕获”消息。

作者使用不同的编译器(WxDev)。 (我使用的是 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;
}

书中的代码图片: enter image description here

最佳答案

对于初学者来说,throw() 规范已被弃用,更喜欢 noexcept。我怀疑你的书更新了多少,无论如何,我建议你看一下这个优秀的 C++ 书籍列表:The Definitive C++ Book Guide and List .要更深入地了解 throw 规范及其不好的原因,请参阅 http://www.gotw.ca/publications/mill22.htm (感谢 user4581301)

现在,答案:

根据 https://en.cppreference.com/w/cpp/language/except_spec

If the function throws an exception of the type not listed in its exception specification, the function std::unexpected is called. The default function calls std::terminate, [...]

所以这本书似乎是正确的,当使用 g++ 时,您会得到预期的行为:https://onlinegdb.com/Sy_7DzUmB

terminate called after throwing an instance of 'char'
Aborted

如果您使用 throw(char) 异常会被捕获。

Microsoft Visual Studio 2019 没有实现那种异常规范:https://learn.microsoft.com/en-us/cpp/error-messages/compiler-warnings/compiler-warning-level-3-c4290?view=vs-2019

A function is declared using exception specification, which Visual C++ accepts but does not implement. Code with exception specifications that are ignored during compilation may need to be recompiled and linked to be reused in future versions supporting exception specifications.

来自:https://learn.microsoft.com/en-us/cpp/cpp/exception-specifications-throw-cpp?view=vs-2019

throw(type): (C++14 and earlier) The function can throw an exception of type type. The compiler accepts the syntax, but interprets it as noexcept(false) [...]

有趣的是,这也是 Herb Sutter 在链接文章中所说的

At least one popular C++ compiler (Microsoft’s, up to version 7.x) parses exception specifications but does not actually enforce them, reducing the exception specifications to glorified comments

最后,这个答案更像是一种好奇,throw() 已从该语言的最新版本中以各种形式弃用(并删除):https://en.cppreference.com/w/cpp/language/except_spec .

首选noexcept:https://en.cppreference.com/w/cpp/language/noexcept_spec

关于c++ - 未处理的异常得到处理(visual studio 2019 这么聪明还是我遗漏了什么?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57365406/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com