Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are your best practices for C++ exception handling? [closed]

I searched the Internet and found a lot of articles about this topic. However, I found there is no complete checklist to verify our code's quality of exception-safety.

So, I want to collect valuable best practices for C++ exception handling from you.

I first list some practices of my own:

  1. Catch all exceptions if any in destructors:

    struct A
    {
        ~A()
        {
            try
            {
                // Here may throw exceptions
            }
            catch (std::runtime_error& e)
            {}
            catch (...)
            {
                logging("...");
            }
        }
    };
    
  2. Add function name, source file name and line numer in exception information. __func__, __FILE__ and __LINE__ are good friends.

  3. Never use exception specifications. The reason is given in the book "C++ Coding Standards".

What are yours?

like image 455
xmllmx Avatar asked Jan 29 '13 18:01

xmllmx


People also ask

What is the best practices for exception handling in C #?

The best practices for Exception Handling in C# are based on logging the exception. The log should be to logging library to keep a record of the exceptions. Log exceptions using log4net, NLog, and other frameworks used for the same purpose.

What is exceptional handling in C?

Exception handling is a mechanism that separates code that detects and handles exceptional circumstances from the rest of your program. Note that an exceptional circumstance is not necessarily an error. When a function detects an exceptional situation, you represent this with an object.


1 Answers

I know this may better fit as a comment than as an answer, but since the resource I'm linking answers all of your questions and more, I thought it would be OK to post it as an answer as well, just to give it more visibility and/or relevance.

And since I couldn't possibly sum it all up better than the original does, I'm not even going to try and do a short summary, because I would risk to distort it or give a biased overview.

Just watch this two-part talk on exception-safe coding by Jon Kalb. That's it.

like image 152
Andy Prowl Avatar answered Oct 26 '22 16:10

Andy Prowl