1

I have heard that in C++11 we should replace throw with noexcept after method declaration :

In C++11, you generally should use noexcept instead. The old throw specification is deprecated.

How to do it in the following code?

template <typename Object>
class Stack
{
public:

    Stack();

    Object & peek() throw(std::runtime_error);

};

Reference link

Please avoid linking to the questions which do not work for std::runtime_error

Community
  • 1
  • 1
barej
  • 1,330
  • 3
  • 25
  • 56
  • This is not noexcept. Simply remove the throw clause, or make it a comment.. – Yakk - Adam Nevraumont May 31 '15 at 13:02
  • possible duplicate of [Difference between C++03 throw() specifier C++11 noexcept](http://stackoverflow.com/questions/12833241/difference-between-c03-throw-specifier-c11-noexcept) – m0nhawk May 31 '15 at 13:04
  • @m0nhawk how does this link deal with `std::runtime_error`? – barej May 31 '15 at 13:05
  • 3
    @barej, *noexcept was added because it's the one reasonably useful use of an exception specifier: knowing when a function won't throw an exception. Thus it becomes a binary choice: functions that will throw and functions that won't throw.* You have comments for communicating when you'll throw which types. – chris May 31 '15 at 13:09
  • @chris so do you mean `throw` can set what to strop throwing while `noexcept` cannot? – barej May 31 '15 at 13:19
  • @barej, Yes, only `throw` checks for specific exceptions. – chris May 31 '15 at 13:43

1 Answers1

0

It was found that dynamic exception specifications were not really useful, which is why they've been deprecated in C++11. The only case where they were deemed useful were empty dynamic exception specification, that is throw(). For this case, the noexcept declaration was introduced as a better alternative, allowing the compiler to perform more aggressive optimizations. (Note that this means that throw() and noexcept are not semantically equivalent and you should only replace the former with the latter if you know that the program will still behave correctly.)

In your case, you don't have an empty throw() so you cannot replace it with noexcept. It is widely agreed upon that in this case, it would be best to simply remove the throw(std::runtime_error) and mention the fact that the function might throw a std::runtime_error but nothing else in the documentation, as Yakk has already suggested in the comments.

5gon12eder
  • 24,280
  • 5
  • 45
  • 92