Today I learned that swap is not allowed to throw an exception in C++.
I also know that the following cannot throw exceptions either:
Destructors
Reading/writing primitive types
Are there any others?
Or perhaps, is there some sort of list that mentions everything that may not throw?
(Something more succinct than the standard itself, obviously.)
There is a great difference between cannot and should not. Operations on primitive types cannot throw, as many functions and member functions, including many operations in the standard library and/or many other libraries.
Now on the should not, you can include destructors and swap. Depending on how you implement them, they can actually throw, but you should avoid having destructors that throw, and in the case of swap, providing a swap operation with the no-throw guarantee is the simplest way of achieving the strong exception guarantee in your class, as you can copy aside, perform the operation on the copy, and then swap with the original.
But note that the language allows both destructors and swap to throw. swap can throw, in the simplest case if you do not overload it, then std::swap performs a copy construction, an assignment and a destruction, three operations that can each throw an exception (depending on your types).
The rules for destructors have changed in C++11, which means that a destructor without exception specification has an implicit noexcept specification which in turn means that if it threw an exception the runtime will call terminate, but you can change the exception specification to noexcept(false) and then the destructor can also throw.
At the end of the day, you cannot provide exception guarantees without understanding your code base, because pretty much every function in C++ is allowed to throw.
So this doesn't perfectly answer you question -- I searched for a bit out of my own curiosity -- but I believe that nothrow guaranteed functions/operators mostly originate from any C-style functions available in C++ as well as a few functions which are arbitrarily simple enough to give such a guarantee. In general it's not expected for C++ programs to provide this guarantee ( When should std::nothrow be used? ) and it's not even clear if such a guarantee buys you anything useful in code that makes regular use of exceptions. I could not find a comprehensive list of ALL C++ functions that are nothrow functions (please correct me if I missed a standard dictating this) other than listings of swap, destructors, and primitive manipulations. Also it seems fairly rare for a function that isn't fully defined in a library to require the user to implement a nothrows function.
So perhaps to get to the root of your question, you should mostly assume that anything can throw in C++ and take it as a simplification when you find something that absolutely cannot throw an exception. Writing exception safe code is much like writing bug free code -- it's harder than it sounds and honestly is oftentimes not worth the effort. Additionally there are many levels between exception unsafe code and strong nothrow functions. See this awesome answer about writing exception safe code as verification for these points: Do you (really) write exception safe code?. There's more information about exception safety at the boost site http://www.boost.org/community/exception_safety.html.
For code development, I've heard mixed opinions from Professors and coding experts on what should and shouldn't throw an exception and what guarantees such code should provide. But a fairly consistent assertion is that code which can easily throw an exception should be very clearly documented as such or indicate the thrown capability in the function definition (not always applicable to C++ alone). Functions that can possible throw an exception are much more common than functions that Never throw and knowing what exceptions can occur is very important. But guaranteeing that a function which divides one input by another will never throws a divide-by-0 exception can be quite unnecessary/unwanted. Thus nothrow can be reassuring, but not necessary or always useful for safe code execution.
In response to comments on the original question:
People will sometimes state that exception throwing constructors are evil when throw in containers or in general and that two-step initialization and is_valid checks should always be used. However, if a constructor fails it's oftentimes unfixable or in a uniquely bad state, otherwise the constructor would have resolved the problem in the first place. Checking if the object is valid is as difficult as putting a try catch block around initialization code for objects you know have a decent chance of throwing an exception. So which is correct? Usually whichever was used in the rest of the code base, or your personal preference. I prefer exception based code as it gives me a feeling of more flexibility without a ton of baggage code of checking every object for validity (others might disagree).
Where does this leave you original question and the extensions listed in the comments? Well, from the sources provided and my own experience worrying about nothrow functions in an "Exception Safety" perspective of C++ is oftentimes the wrong approach to handling code development. Instead keep in mind the functions you know might reasonably throw an exception and handle those cases appropriately. This is usually involving IO operations where you don't have full control over what would trigger the exception. If you get an exception that you never expected or didn't think possible, then you have a bug in your logic (or your assumptions about the function uses) and you'll need to fix the source code to adapt. Trying to make guarantees about code that is non-trivial (and sometimes even then) is like saying a sever will never crash -- it might be very stable, but you'll probably not be 100% sure.
If you want the in-exhaustive-detail answer to this question go to http://exceptionsafecode.com/ and either watch the 85 min video that covers just C++03 or the three hour (in two parts) video that covers both C++03 and C++11.
When writing Exception-Safe code, we assume all functions throw, unless we know different.
In short,
*) Fundamental types (including arrays of and pointers to) can be assigned to and from and used with operations that don't involve user defined operators (math using only fundamental integers and floating point values for example). Note that division by zero (or any expression whose result is not mathematically defined) is undefined behavior and may or may not throw depending on the implementation.
*) Destructors: There is nothing conceptually wrong with destructors that emit exceptions, nor does the standard prohibited them. However, good coding guidelines usually prohibit them because the language doesn't support this scenario very well. (For example, if destructors of objects in STL containers throw, the behavior is undefined.)
*) Using swap() is an important technique for providing the strong exception guarantee, but only if swap() is non-throwing. In general, we can't assume that swap() is non-throwing, but the video covers how to create a non-throwing swap for your User-Defined Types in both C++03 and C++11.
*) C++11 introduces move semantics and move operations. In C++11, swap() is implemented using move semantics and the situation with move operations is similar to the situation with swap(). We cannot assume that move operations do not throw, but we can generally create non-throwing move operations for the User-Defined Types that we create (and they are provided for standard library types). If we provide non-throwing move operations in C++11, we get non-throwing swap() for free, but we may choose to implement our own swap() any way for performance purposes. Again, this is cover in detail in the video.
*) C++11 introduces the noexcept operator and function decorator. (The "throw ()" specification from Classic C++ is now deprecated.) It also provides for function introspection so that code can be written to handle situations differently depending on whether or not non-throwing operations exist.
In addition to the videos, the exceptionsafecode.com website has a bibliography of books and articles about exceptions which needs to be updated for C++11.
Related
I saw that C++ 11 added the noexcept keyword. But I don't really understand why is it useful.
If the function throws when it's not supposed to throw - why would I want the program to crash?
So when should I use it?
Also, how will it work along with compiling with /Eha and using _set_se_translator? This means that any line of code can throw c++ exception - because it might throw a SEH exception (Because of accessing protected memory) and it will be translated to c++ exception.
What will happen then?
The primary use of noexcept is for generic algorithms, e.g., when resizing a std::vector<T>: for an efficient algorithm moving elements it is necessary to know ahead of time that none of the moves will throw. If moving elements might throw, elements need to be copied instead. Using the noexcept(expr) operator the library implementation can determine whether a particular operation may throw. The property of operations not throwing becomes part of the contract: if that contract is violated, all bets are off and there may be no way to recover a valid state. Bailing out before causing more damage is the natural choice.
To propagate knowledge about noexcept operations do not throw it is also necessary to declare functions as such. To this end, you'd use noexcept, throw(), or noexcept(expr) with a constant expression. The form using an expression is necessary when implementing a generic data structure: with the expression it can be determined whether any of the type dependent operations may throw an exception.
For example, std::swap() is declared something like this:
template <typename T>
void swap(T& o1, T& o2) noexcept(noexcept(T(std::move(o1)) &&
noexcept(o1 = std::move(o2)));
Based on noexcept(swap(a, b)) the library can then choose differently efficient implementations of certain operations: if it can just swap() without risking an exception it may temporarily violate invariants and recover them later. If an exception might be thrown the library may instead need to copy objects rather than moving them around.
It is unlikely that the standard C++ library implementation will depend on many operations to be noexcept(true). The probably the operations it will check are mainly those involved in moving objects around, i.e.:
The destructor of a class (note that destructors are by default noexcept(true) even without any declaration; if you have destructor which may throw, you need to declare it as such, e.g.: T::~T() noexcept(false)).
The move operators, i.e. move construction (T::T(T&&)) and move assignment (T::operator=(T&&)).
The type's swap() operations (swap(T&, T&) and possibly the member version T::swap(T&)).
If any of these operations deviates from the default you should declare it correspondingly to get the most efficient implementation. The generated versions of these operations declare whether they are throwing exceptions based on the respective operations used for members and bases.
Although I can imagine that some operations may be added in the future or by some specific libraries, I would probably not declaration operations as noexcept for now. If other functions emerge which make a difference being noexcept they can be declared (and possible changed as necessary) in the future.
The reason that the program may crash is because noexcept tells the optimizer your code won't throw. If it does - well, there's no way to predict what will happen with optimized code.
As for MSVC++, you'd have to check what happens when they implement noexcept. From a Standard viewpoint, SEH is undefined behavior. Accessing protected memory can already crash right now.
For STL containers (so far, std::vector<> and std::deque<>), I'm looking for documentation that says exactly when they throw exceptions. Something like, "It throws X in situation A. It throws Y in situation B. It throws no other exceptions under any circumstances."
I'd like to reassure my exception-phobic colleagues that we know exactly what can trigger exceptions in the STL classes we use.
The most accurate information will come from the C++ standard matching your compiler, and compiler documentation. However, the spec costs money. If you're willing to settle for a few typos, the draft C++11 specification can be found here: http://open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf for free, and the latest publicly available draft (preparing for C++14) seems to be http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf.
The number 1 used container is vector, so lets go over that.
Technically the only vector member that throws an exception is at, if given an out of range index. (tada! we're done!)
Less technically, vector assign/insert/emplace/reserve/resize/push_back/emplace_back/shrink_to_fit/etc can cause a resize, which uses std::allocator<T>:allocate, which can throw std::bad_alloc in theory. In weird situations with weird allocators, swap can also trigger this too. On some systems (Linux), this pretty much never happens, because it only throws if it runs out of virtual memory, and often the program will run out of physical memory first, and the OS will simply kill the whole program. That happens regardless of exceptions though, so this doesn't count against C++ exceptions.
Probably relevant is that the elements in a vector can throw any exception when copied, which affects constructors, assignment, insert/emplace/push_back/emplace_back, reserve, resize/shrink_to_fit. (If your element has a noexcept move constructor and move assignment, and it really really really should, then happens only when copying the entire vector).
The spec details exactly what exceptions are thrown and often also specifies under exactly what conditions they're thrown.
The C++ standard documents when exceptions will be thrown and under what circumstances for the standard library containers. There are also general rules about which methods will not throw exceptions for containers.
Alternatively, you can search the headers for throw (or the equivalent macro) to determine under what circumstances exceptions will trigger.
Just as I can see in cppreference, the classic "throw" declaration lists is now deprecated in C++11. What is the reason of leaving this mechanism and how should I have to specify what exceptions throws a function of mine?
For more detailed reasoning, see: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3051.html
As expressed in the national body comment above, exception specifications have not proven useful in practice. There are numerous discussions of the problems with exception specifications in C++ (see, e.g., [Sutter02], [Boost03]), but the main issues are:
Run-time checking: C++ exception specifications are checked at runtime rather than at compile time, so they offer no programmer guarantees that all exceptions have been handled. The run-time failure mode (calling std::unexpected()) does not lend itself to recovery.
Run-time overhead: Run-time checking requires the compiler to produce additional code that also hampers optimizations.
Unusable in generic code: Within generic code, it is not generally possible to know what types of exceptions may be thrown from operations on template arguments, so a precise exception specification cannot be written.
In practice, only two forms of exception-throwing guarantees are useful: an operation might throw an exception (any exception) or an operation will never throw any exception. The former is expressed by omitting the exception-specification entirely, while the latter can be expressed as throw() but rarely is, due to performance considerations.
[N3050] introduces a new kind of exception specification, noexcept, the specifies that the function will not throw any exceptions. Unlike throw(), noexcept does not require the compiler to introduce code to check whether an exception is thrown. Rather, if a function specified as noexcept is exited via an exception, the result is a call to std::terminate().
With the introduction of noexcept, programmers can now express the two kinds of exception guarantees that are useful in practice, without additional overhead. This paper therefore proposes to deprecate "dynamic" exception specifications, i.e., those that are written as throw(type-id-listopt).
The answer Peter gave does not hit the actual problem of exception specifications for the implementor and user:
Exception specifications cause the program to terminate (or more precisely call termination handlers) if the implementor failed to uphold the guarantee to only throw the defined exceptions.
Thus by calling a method with a exception specification you as a library user are making your own code more prone to complete failure/termination. If the library function runs out-of-memory (std::bad_alloc), you will not get a chance to catch, but you will be terminated instead.
Thus, the original goal of communicating the most likely failure options and asking you as the user to handle them was not achieved.
As an implementor on the other side, you cannot really call any other methods any more which do not have exception specifications, because these might cause you to terminate your callers. A terrible place to be in.
The conclusion is that C++ should have just gone the way that Java did it:
If you call a method with exception specification and you have an exception specification yourself, then you must catch the exception or specify it in your own exception specification.
The compiler enforces this and no other runtime effects.
Noexcept (since C++11) suffers the same conceptual mistake, since it will also cause run-time termination if the specification is not adhered too, i.e. a method throws that was declared not to. This makes noexcept impossible to use for anything serious but the most contained cases (move constructors come to mind).
They produce slower and bigger code, because libc++ has to check if any exception propagating out of a function violates it's exception specification and call std::unexpected. This is hardly ever useful, and is worse than just documenting the exceptions a function throws yourself.
As you might know C++11 has noexcept keyword. Now ugly part about it is this:
Note that a noexcept specification on a function is not a compile-time
check; it is merely a method for a programmer to inform the compiler
whether or not a function should throw exceptions.
http://en.cppreference.com/w/cpp/language/noexcept_spec
So is this a design failure on the committee part or they just left it as an exercise for the compile writers :) in a sense that decent compilers will enforce it, bad ones can still be compliant?
BTW if you ask why there isnt a third option ( aka cant be done) reason is that I can easily think of a (slow) way to check if function can throw or not. Problem is off course if you limit the input to 5 and 7(aka I promise the file wont contain anything beside 5 and 7) and it only throws when you give it 33, but that is not a realistic problem IMHO.
The committee pretty clearly considered the possibility that code that (attempted to) throw an exception not allowed by an exception specification would be considered ill-formed, and rejected that idea. According to $15.4/11:
An implementation shall not reject an expression merely because when executed it throws or might throw an exception that the containing function does not allow. [ Example:
extern void f() throw(X, Y);
void g() throw(X) {
f(); // OK
}
the call to f is well-formed even though when called, f might throw exception Y that g does not allow. —end example ]
Regardless of what prompted the decision, or what else it may have been, it seems pretty clear that this was not a result of accident or oversight.
As for why this decision was made, at least some goes back to interaction with other new features of C++11, such as move semantics.
Move semantics can make exception safety (especially the strong guarantee) much harder to enforce/provide. When you do copying, if something goes wrong, it's pretty easy to "roll back" the transaction -- destroy any copies you've made, release the memory, and the original remains intact. Only if/when the copy succeeds, you destroy the original.
With move semantics, this is harder -- if you get an exception in the middle of moving things, anything you've already moved needs to be moved back to where it was to restore the original to order -- but if the move constructor or move assignment operator can throw, you could get another exception in the process of trying to move things back to try to restore the original object.
Combine this with the fact that C++11 can/does generate move constructors and move assignment operators automatically for some types (though there is a long list of restrictions). These don't necessarily guarantee against throwing an exception. If you're explicitly writing a move constructor, you almost always want to ensure against it throwing, and that's usually even pretty easy to do (since you're normally "stealing" content, you're typically just copying a few pointers -- easy to do without exceptions). It can get a lot harder in a hurry for template though, even for simple ones like std:pair. A pair of something that can be moved with something that needs to be copied becomes difficult to handle well.
That meant, if they'd decided to make nothrow (and/or throw()) enforced at compile time, some unknown (but probably pretty large) amount of code would have been completely broken -- code that had been working fine for years suddenly wouldn't even compile with the new compiler.
Along with this was the fact that, although they're not deprecated, dynamic exception specifications remain in the language, so they were going to end up enforcing at least some exception specifications at run-time anyway.
So, their choices were:
Break a lot of existing code
Restrict move semantics so they'd apply to far less code
Continue (as in C++03) to enforce exception specifications at run time.
I doubt anybody liked any of these choices, but the third apparently seemed the last bad.
One reason is simply that compile-time enforcement of exception specifications (of any flavor) is a pain in the ass. It means that if you add debugging code you may have to rewrite an entire hierarchy of exception specifications, even if the code you added won't throw exceptions. And when you're finished debugging you have to rewrite them again. If you like this kind of busywork you should be programming in Java.
The problem with compile-time checking: it's not really possible in any useful way.
See the next example:
void foo(std::vector<int>& v) noexcept
{
if (!v.empty())
++v.at(0);
}
Can this code throw?
Clearly not. Can we check automatically? Not really.
The Java's way of doing things like this is to put the body in a try-catch block, but I don't think it is better than what we have now...
As I understand things (admittedly somewhat fuzzy), the entire idea of throw specifications was found to be a nightmare when it actually came time to try to use it in useful way.
Calling functions that don't specify what they throw or do not throw must be considered to potentially throw anything at all! So the compiler, were it to require that you neither throw nor call anything that might throw anything outside of the specification you're provided actually enforce such a thing, your code could call almost nothing whatsoever, no library in existence would be of any use to you or anyone else trying to make any use of throw specifications.
And since it is impossible for a compiler to tell the difference between "This function may throw an X, but the caller may well be calling it in such a way that it will never throw anything at all" -- one would forever be hamstrung by this language "feature."
So... I believe that the only possibly useful thing to come of it was the idea of saying nothrow - which indicates that it is safe to call from dtors and move and swap and so on, but that you're making a notation that - like const - is more about giving your users an API contract rather than actually making the compiler responsible to tell whether you violate your contract or not (like with most things C/C++ - the intelligence is assumed to be on the part of the programmer, not the nanny-compiler).
Although this topic has been extensively discussed on SO, I'd like to clarify a few things that are still not clear to me so, considering the following facts:
10 years ago, Herb Sutter was telling us to refrain from using this functionality.
Specifying the possible exceptions that a function / method may throw does not force the compiler to yell at you when you decide to change the function's body and throw a new type of exception, forgetting by mistake to change the exception specification in the function's declaration.
If you have a very high level function that calls several other high level functions, which each run tons of code to produce the results, then I can imagine the maintenance from hell nightmare, when I would have to specify ALL the errors which the first function may throw, and this list would have to include all the exceptions the inner functions may throw and so on, thus creating tight coupling between high and low level functions, which is quite undesirable. On the other hand, we derive all exceptions from std::runtime_error, which we know is a good practice and we could specify that the high level functions just throw std::runtime_error and be done with it. But wait a minute... Where do we actually catch the exceptions? Would it not be rather odd / nasty / bad to enclose a call to one of these high level functions in a try / catch block, which catches a MyVerySpecific exception, when the high level function is supposed to throw only std::runtime_error??? Would it be any good to catch specific exceptions in lower level functions, which are not able to do anything about them but pass them on in a more generic container, with more information appended to them? I certainly don't want to write try / catch blocks in every function that I write, just to format exceptions. It would be like requiring every function to validate its parameters, and that can drive people insane, when they need to change something in a low level function.
Questions:
Do Herb Sutter's rants about exception specification still hold today? Has anything changed since then? I am mostly interested in pre-C++0x standards. If yes, I guess we can consider this topic closed.
Since it seems that the compiler mostly ignores these exception specifications, and when catching exceptions, in 99% of the cases, one would use catch (const CustomException &ex), how would one specify that a function throws CustomException? throw(CustomExecption) or throw (CustomException &) or throw (const CustomException &)? I have seen all variations, and, although I would go for the first one, do the others make any sense / add any benefits?
How would one actually use this functionality, and, at the same time, avoid the fallacies illustrated in the above 3rd fact?
EDIT: Suppose that we're building a library. How will its users know what exceptions to expect, if we don't use exception specification? They will certainly not see what functions will be called internally by the API methods...
1/ Do Herb Sutter's rants about exception specification still hold today? Has anything changed since then? I am mostly interested in pre-C++0x standards. If yes, I guess we can consider this topic closed.
Yes, they still hold.
Exceptions specifications are:
half-way implemented (function pointers don't specify exceptions, for example)
not checked at compile-time, but leading to termination at runtime !!
In general, I would be against exceptions specifications, because it causes a leak of implementation details. Look at the state of Java exceptions...
In C++ in particular ? Exceptions specifications are like shooting yourself in the foot since the tiniest error in documentation may lead to a std::terminate call. Note that almost all functions may throw a std::bad_alloc or a std::out_of_range for example.
Note: Since C++11, throw() was deprecated and now with C++17 it is gone; instead, from C++17 on, the noexcept(false) specifier can be used. It is better supported in function pointers, but still leads to termination at run-time rather than errors at compile-time.
2/ Since it seems that the compiler mostly ignores these exception specifications, and when catching exceptions, in 99% of the cases, one would use catch (const CustomException &ex), how would one specify that a function throws CustomException? throw(CustomExecption) or throw (CustomException &) or throw (const CustomException &)? I have seen all variations, and, although I would go for the first one, do the others make any sense / add any benefits?
The compiler does not ignore the exceptions specifications, it sets up very vigilant watchdogs (which axes) to make sure to kill your program in case you had missed something.
3/ How would one actually use this functionality, and, at the same time, avoid the fallacies illustrated in the above 3rd fact?
Your customer will appreciate if it stays informal, so the best example is:
void func(); // throw CustomException
and this lets you focus on the exceptions that matter too, and let "unimportant" exceptions slip through. If a consumer wants them all ? catch(std::exception const& e) works.
4/ EDIT: Suppose that we're building a library. How will its users know what exceptions to expect, if we don't use exception specification? They will certainly not see what functions will be called internally by the API methods...
Do they have to ?
Document what matters, std::exception or ... take care of the unexpected.
Do Herb Sutter's rants about exception specification still hold today? Has anything changed since then?
I wouldn't call that a rant. He just pointed out problems related to exception specifications.
Yes, it still holds. As explained in the text, if a not specified exception is throw, the program terminates, and that is not acceptable for 99% applications.
how would one specify that a function throws CustomException?
class A
{
//...
void foo() throws( CustomException );
};
How would one actually use this functionality, and, at the same time, avoid the fallacies illustrated in the above 3rd fact?
By looking at the function declaration, the user knows which exceptions can be thrown. The problem is when a new exception needs to be thrown, then all functions declarations needs to be changed.
Suppose that we're building a library. How will its users know what exceptions to expect, if we don't use exception specification?
By reading the documentation.