I have 2 questions about non-throwing functions:
-
Why make a function non-throwing?
-
How to make a function non-throwing? If the code inside the function actually may
throw, then should I still make it non-throwing?
Here is an example:
void swap(Type t1, Type t2) throw()
{
//swap
}
If the code in swap won’t throw at all, should I still append throw()? Why?
throw()(ornoexceptin C++11) is useful for two reasons:Non-throwing functions are very important for writing exception safe code. For instance, the usual way of writing an exception safe
operator=is via a non-throwingswap()function.On the other hand, other exception specifications are useless and have been justly deprecated in the current standard. They don’t mix well at all with templates and are too expensive to enforce.
Now, if you use a
noexceptspecification in a function that might actually throw, all bets are off. Even if your compiler does not terminate the program when an exception leaves the function (VS does not do it for runtime efficiency reasons, for instance), your code might not do what you thought because of optimisations. For example:If
a()actually throws andb()has side effects, the function behaviour will be unpredictable, because your compiler may decide to executeb()beforea(), since you have told it that no exceptions will be thrown.EDIT: Now for the second part of your question: how to make a function non-throwing?
First you need to ask yourself whether your function should really be non-throwing. For instance:
Since operator
newcan throw astd::bad_alloc,CreateInstance()can throw. You could try to avoid it with a try-catch block, handling or swallowing any exceptions that may be thrown inside thetryblock, but would that really be sensible? For instance:Problem solved, it seems, but would your callers be prepared for
CreateInstance()returningnull? If not, a crash will ensue when they try to use that pointer. Besides, astd::bad_allocusually means that you have run out of memory and you would just be postponing the problem.So be careful: some functions can be made non-throwing, but others should be allowed to throw. Exception safety is not a trivial matter.