1

I want to document that function throws exception

  1. Are those samples below equivalent?
  2. What is the preferred way?
void validate_input(const std::string &on) throw(...)
void validate_input(const std::string &on) noexcept(false)
// throws std::runtime_error if input is invalid
void validate_input(const std::string &on)
random
  • 3,868
  • 3
  • 22
  • 39
  • 2
    Not just he third option. – Robert Andrzejuk Sep 09 '19 at 16:27
  • 3
    *I want to document that function throws exception* I would like to change your mind on that. Instead of specifying what can throw, I would rather say everything can, except for the that explicitly can't. By doing that you can gain performance optimizations when you can guarantee there wont be an exception, and get the normal behavior when you can't. For more see: https://stackoverflow.com/questions/10787766/when-should-i-really-use-noexcept – NathanOliver Sep 09 '19 at 16:50

2 Answers2

3

The third one.

You should definitely write a comment explaining what exceptions the function may throw, and what that means when it does.

Otherwise, people using your function have to examine its implementation and work it out for themselves. Every time. Not good!

Put the comment alongside the ones you already have (right??) listing preconditions and postconditions and explaining what the function does.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
2
  1. Are those samples below equivalent?

throw(...) is different from the two others, is deprecated and going to be removed in a future standard.

Second and third are mutually equivalent (exceptions apply 1) as far as the language is concerned. Lack of exception specification implies that the function may throw (also 1).

Documenting what exceptions are thrown and in which situations is a good practice.


1 Deallocation functions and destructors are implicitly non-throwing but can be explicitly specified otherwise. Implicitly generated or defaulted special member functions etc. may "inherit" specification from base / members i.e. they are implicitly non-throwing unless a base or a member is potentially throwing.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • 1
    *Second and third are mutually equivalent as far as the language is concerned. Lack of exception specification implies that the function may throw.* This does not hold true for implicit constructors, defaulted special member functions, or destructors. – NathanOliver Sep 09 '19 at 16:35
  • @NathanOliver added mention of exceptions. – eerorika Sep 09 '19 at 16:42
  • You've got it backwards. Destructors are `noexcept(true)` by default and only `noexcept(false)` if something in the chain (sub object, base) is `noexcept(false)`. – NathanOliver Sep 09 '19 at 16:45
  • @NathanOliver Should be better now. Harder to mix up in English. – eerorika Sep 09 '19 at 16:48