Question

I need to implement an exception handling system for a very large C++ code. I need to implement a standard which meets the following specifications:

  • Print out the call trace when an exception is thrown
  • Allow the developer to specify optional additional information about the state of a function when the exception is called. (e.g. the value of a counter during an iteration)
  • Easy to implement (since I will not be able to do it myself)
  • Uninvasive
  • Portable

It seems to me as though putting try/catch blocks in every single function is the only possible solution, but this seems generally fround upon and considered to be bad practice. It is also clumsy and difficult to maintain/implement consistently.

I have also looked into libraries like stacktrace, but they seem limited on portability and I would have to sacrifice the ability for optional additional state information.

Edit: what is the best way to do this?

Was it helpful?

Solution

Good list of requirements! Of course taking stack trace is not portable but all popular compilers allow to take stack trace. You may start looking at backtrace/backtrace_symbols functions (gcc, clang). Here is an example.

Regarding second point - you'd better limit your exception class with string message. In my experience passing arbitrary information is not really useful (what other handling options do you have except output error message?). If you still insist on linking typed data to exception boost::exception will do the job.

You also may want to add "chained exception" item to your list of requirements. It's useful feature especially when your application has several layers and you rethrow original exception one or more times. C++11 allows to implement chained exception easily. See example of implementation and test cases that show how to use it.

Regarding 4th point - C++ exceptions are not invasive (in a sense). You even don't have to catch it. If you inherit your exception class from std::exception and provide proper implementation of what() the catch side will handle whatever you throw.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top