Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone explain C++ exception specifications to me?

Tags:

c++

Can anyone explain Exception Specifications as used in C++ ?

  • When are they used (I have rarely seen it used in code)
  • What are the pros and cons (benefits/disadvantages) of using exception specifications?
like image 475
skyeagle Avatar asked May 03 '10 22:05

skyeagle


People also ask

What do you understand by exception specification?

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.

What happens if a function throws an exception that is not listed in the function exception specification list?

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().

What is dynamic exception specification?

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.

Why are dynamic exception specifications are deprecated in C++ 11?

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.


2 Answers

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
{
    /* ... */
{
like image 134
AshleysBrain Avatar answered Nov 09 '22 04:11

AshleysBrain


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.

like image 25
pm100 Avatar answered Nov 09 '22 02:11

pm100