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:
Catch all exceptions if any in destructors:
struct A
{
~A()
{
try
{
// Here may throw exceptions
}
catch (std::runtime_error& e)
{}
catch (...)
{
logging("...");
}
}
};
Add function name, source file name and line numer in exception information. __func__
, __FILE__
and __LINE__
are good friends.
Never use exception specifications. The reason is given in the book "C++ Coding Standards".
What are yours?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With