I am writing a custom C++ exception class (so I can pass exceptions occuring in C++ to another language via a C API).
My initial plan of attack was to proceed as follows:
//C++
myClass
{
public:
myClass();
~myClass();
void foo() // throws myException
int foo(const int i, const bool b) // throws myException
} * myClassPtr;
// C API
#ifdef __cplusplus
extern "C" {
#endif
myClassPtr MyClass_New();
void MyClass_Destroy(myClassPtr p);
void MyClass_Foo(myClassPtr p);
int MyClass_FooBar(myClassPtr p, int i, bool b);
#ifdef __cplusplus
};
#endif
I need a way to be able to pass exceptions thrown in the C++ code to the C side. The information I want to pass to the C side is the following:
(a). What (b). Where (c). Simple Stack Trace (just the sequence of error messages in order they occured, no debugging info etc)
I want to modify my C API, so that the API functions take a pointer to a struct ExceptionInfo, which will contain any exception info (if an exception occured) before consuming the results of the invocation.
So an C++ method exposed in the C API would be implemented something like this:
// I must admit there is something freakishly 'hackish' about this sort of implementation (maintenance nightmare aside) - ther must be a better way?
// ExceptionInfo default ctor initialized to no error
void MyClass::foobarTrappedExceptionWrapper(ExceptionInfo& ei)
{
try {
// call foobar ...
foobar();
}
catch(fast_exception& fe)
{
switch (fe.errcode())
{
//package exception info into ei for C consumption
}
}
catch(std::exception &e)
{
//package exception info into ei for C consumption
}
}
Implementation of each of the C++ methods exposed in the C API needs to be enclosed in a try/catch statement (see above snippet). The performance implications for this seem quite serious (according to this article):
"It is a mistake (with high runtime cost) to use C++ exception handling for events that occur frequently, or for events that are handled near the point of detection."
At the same time, I remember reading somewhere in my C++ days, that all though exception handling is expensive, it only becmes expensive when an exception actually occurs. So, which is correct?. what to do?. Is there an alternative way that I can trap errors safely and pass the resulting error info to the C API?. Or is this a minor consideration (the article after all, is quite old, and hardware have improved a bit since then).
[Edit]
Removed question2, since I found a way to create a simple stack trace here.