Can anyone explain Exception Specifications as used in C++ ?
Exception specifications are a C++ language feature that indicate the programmer's intent about the exception types that can be propagated by a function. You can specify that a function may or may not exit by an exception by using an exception specification.
If a function throws an exception not listed in its exception specification, the function unexpected(), defined in the C++ standard library, is invoked. The default behavior of unexpected() is to call terminate(). (In some situations, it may be necessary to override the actions performed by unexpected().
A function with a non-throwing dynamic exception specification does not allow any exceptions. A dynamic exception specification is not considered part of a function's type. If the function throws an exception of the type not listed in its exception specification, the function std::unexpected is called.
Dynamic exception specifications are deprecated. That's a warning from the standards committee that they might be removed in a future version of the standard. In the meantime, they are legal and their behavior is well defined.
The important thing to know is: exception specifications are deprecated in the next revision of C++, except for the no-throw specifier (throw()
), which is basically officially saying "don't use them".
Putting throw()
after a function means the function does not throw any exceptions. If it does anyway, the application will be terminated (probably - the unexpected handler is called), so the rest of your application can use that function knowing it will not throw an exception. This is can be handy for writing exception-safe code.
Example:
void MyFunction() throw() // does not throw any exceptions
{
/* ... */
{
They are generally regarded as a bad idea.
They say what a method will throw. The downside is that if that method throws anything else then your app terminates. So it's a guarantee but not in the same way that Java does it. And it adds the overhead of inspection.
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