Josh
Josh

Reputation: 6272

Is it safe to use the throw() suffix on a function containing std::string?

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

Answers (3)

D_E
D_E

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

Matthieu M.
Matthieu M.

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

Ben Voigt
Ben Voigt

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:

  • Nothing your function does can throw, even indirectly

or

  • Your function catches all such exceptions and exits normally (no rethrow).

Upvotes: 2

Related Questions