exit() call inside a function which should return a reference

前端 未结 4 1530
囚心锁ツ
囚心锁ツ 2020-11-27 08:13

In a library I have a function which searches for a key in a database and return a non-const reference to an object. I want to handle the case in which the key is not found,

相关标签:
4条回答
  • 2020-11-27 08:45

    This situation is so bad that the program cannot continue, so I print a message to help to spot the bug and call exit(1)

    No. If this code is part of a library, the library should not be the one deciding if the application should exit or not.

    What if a file is open and needs to be closed, or some other resource needs to be cleaned up, or if the user of your DB class wants to log the error and continue doing something else?

    The answer is anything but what you're doing now. Throw an exception, return an error code, etc. but don't close the application down within library or class code.

    Believe it or not, there was a commercial DB library that did exactly what you're doing (closing the app down). They got a lot of angry responses from users of their library as to why they're shutting the application down unexpectedly. And you know what -- the answer given to the customers was that "we felt the error was severe enough to stop the application, because our library can't continue to work properly". That is not only bad reasoning, it borders on arrogance, and the customers let them know that.

    0 讨论(0)
  • 2020-11-27 08:46

    The answer, as the other respondents, said, should be: throw an exception...

    Type & get(const Key & k) {
         if( !my_db.key_exists(k) ) {
              std::stringstream error;
              error << "key " << k << " not found";
              throw std::runtime_error(error);
         }
         return my_db.at(k);
    }
    
    0 讨论(0)
  • 2020-11-27 08:57

    Exceptions

    This is a common situation in many programs. To overcome this, Exceptions are used.

    • To handle unexpected situations, new Exceptions are created and "thrown" from the code.
    • Then they have to be "caught" by the program calling the function.

    You can read more about exceptions here.

    Hope this helps.

    0 讨论(0)
  • 2020-11-27 09:00

    A library should never exit the hostest application.

    use "return null", get into an "inconsistent state" whichin to every call you return NULL.
    the library user will have to handle it.

    or exceptions...

    0 讨论(0)
提交回复
热议问题