Here is from http://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm
#include <iostream> #include <exception> using namespace std; struct MyException : public exception { const char * what () const throw () { return "C++ Exception"; } };
I understand the const
after what
means the function does not modify any members of the struct, but what does the throw()
at the end mean?
An empty exception specification guarantees that the function does not throw any exception. For example, the function no_problem() guarantees not to throw an exception: extern void no_problem() throw(); If a function declaration does not specify an exception specification, the function can throw exceptions of any type.
In /std:c++17 mode, throw() is an alias for noexcept(true) . In /std:c++17 mode and later, when an exception is thrown from a function declared with any of these specifications, std::terminate is invoked as required by the C++17 standard.
C doesn't support exceptions. You can try compiling your C code as C++ with Visual Studio or G++ and see if it'll compile as-is. Most C applications will compile as C++ without major changes, and you can then use the try... catch syntax.
When an exception is thrown using the throw keyword, the flow of execution of the program is stopped and the control is transferred to the nearest enclosing try-catch block that matches the type of exception thrown. If no such match is found, the default exception handler terminates the program.
It means it won't throw any exceptions. This is an important guarantee for a function like what
, which is usually called in exception handling: you don't want another exception to be thrown while you're trying to handle one.
In C++11, you generally should use noexcept
instead. The old throw specification is deprecated.
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