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;
}
Picture of the code from the book:

For starters, throw() specifications are deprecated, prefer noexcept. I question how updated your book is, regardless, I suggest you take a look at this list of good C++ books: The Definitive C++ Book Guide and List. For a more in-depth look on throw specification and why it is bad, see http://www.gotw.ca/publications/mill22.htm (thanks user4581301)
Now, to the answer:
According to 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, [...]
So the book seems to be right, and when using g++ you get the expected behavior: https://onlinegdb.com/Sy_7DzUmB
terminate called after throwing an instance of 'char'
Aborted
If you use throw(char) the exception gets caught.
Microsoft Visual Studio 2019 does not implement that kind of exception specification: 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.
And from: 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 typetype. The compiler accepts the syntax, but interprets it as noexcept(false) [...]
Interestingly enough this is also what Herb Sutter states in the linked article
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
Finally, this answer is more a curiosity, throw() has been deprecated (and also removed) in its various forms from the more recent versions of the language: https://en.cppreference.com/w/cpp/language/except_spec .
Prefer noexcept: https://en.cppreference.com/w/cpp/language/noexcept_spec
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With