Reputation: 6272
I have a member function that doesn't throw anything so i appended the throw()
suffix to the end of it, indicating that it won't throw any exceptions.
My question is, in the function I make use of several std::string
, and lets say something goes wrong in the initialization of the std::string
, and it throws bad_alloc
or out_of_range
(or what ever else can go wrong with a std::string).
Is it still safe to still add the throw()
suffix?
Upvotes: 4
Views: 226
Reputation: 1196
Herb Sutter says that
exception specifications confer a lot less benefit than they're worth
It can cause more problems than bring benefits. So, you should think twise before doing that.
Upvotes: 4
Reputation: 299960
Two things.
First: the throw()
specification add a runtime check that the function does not throw, calling std::unexpected_exception
if the promise is broken, which will terminate the program.
Second: throw()
is not advised, and has been deprecated in C++11. In C++11 you can use noexcept
instead (or the more malleable form noexcept(boolean-expression)
). No runtime check is created, and the behavior is undefined if the function throws.
Upvotes: 2
Reputation: 283713
The exception specification makes a promise about all code which runs inside the function, whether you wrote it or not.
If std::string
throws from inside your function, that promise is broken, and your program fails. (std::unexpected
exception, which normally means your program terminates hard)
The throw()
specification is proper only if:
or
Upvotes: 2