I'm pondering on using exception handling in some libraries I'm writing. The code base may ultimately be implemented in a number of dlls. I know that using exception handling across dlls is a bad idea - however, would it be safe to do the following?
class IDllSafeException
{
public:
virtual void AddRef() = 0;
virtual void Release() = 0;
virtual int GetErrorCode() const = 0;
virtual const char * What() const = 0;
};
Assuming this is a valid approach, I'd really like to catch by value, rather than pointer. That way I could have a wrapper class which automatically calls Release().
Thus...
template <typename T>
class SafeExceptionT
{
public:
SafeExceptionT(T *);
SafeExceptionT(SafeExceptionT &);
SafeExceptionT & operator=(SafeExceptionT &);
~SafeExceptionT();
int GetErrorCode() const;
const char * What() const;
private:
T * m_pException;
};
typedef SafeExceptionT<IDllSafeException> SafeException;
Being a template means all catch blocks would generate their own layout and call can m_pException->Release() in the destructor (using AddRef() when copying occurs). Also I could implement different types of exceptions as needed.
My catch block would then look like this...
try
{
ThrowSomething();
}
catch(SafeException except)
{
const char * psz = except.What();
int nErrorCode = except.GetErrorCode();
}
...
void ThrowSomething()
{
// Concrete implementation omitted for brevity
throw new DllSafeException(1, "something went wrong");
}
I would have thought that would work but my exception handler does not get caught, even though I've a non-explicit constructor for SafeException.
However I can only seem to catch via pointer...
try
{
ThrowSomething();
}
catch(SafeException except)
{
/// IGNORED!
...
}
catch(IDllSafeException * pExcept)
{
// CAUGHT BY POINTER but we now have to micro-manage.
const char * psz = pExcept->What();
int nErrorCode = pExcept->GetErrorCode();
pExcept->Release();
}
Are there special rules for how types are matched in exception handlers?
Releaseand reinventing smart pointers. - user7860670