I would like to encapsulate Win32 errors (returned from GetLastError ()) in some form of exception class. However, instead of having a single Win32 exception, I would like to have a specialized exception for common errors such as ERROR_ACCESS_DENIED.
For example, I would have classes declared as follows:
class WindowsException : public std::exception { public: static WindowsException Create(DWORD lastError);
However, I would like the Win32 exception to be responsible for choosing the right exception to return. That is, the exception thrower should look like this:
int DangerousMethod() { throw WindowsAPI::WindowsException::Create(GetLastError()); }
and the sight could look like this:
try { DangerousMethod(); } catch(WindowsAPI::ErrorAccessDeniedException ex) { //Code for handling ERROR_ACCESS_DENIED } catch(WindowsAPI::WindowsException ex) { //Code for handling other kinds of error cases. }
My problem is that if the WindowsException :: Create factory method returns a WindowsException, then the subtype (potentially ErrorAccessDeniedException) is cut to the base type. That is, an instance cannot be polymorphic. I do not want to use the new'd pointer because this will cause the exception handler to delete it when it is done.
Does anyone know of a design solution that would be possible to solve this problem elegantly?
Billy3
c ++ design-patterns exception-handling
Billy oneal
source share