C ++ Exception Design Scheme

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); //blah }; class ErrorAccessDeniedException : public WindowsException { public: //blah }; 

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

+6
c ++ design-patterns exception-handling
source share
2 answers

Edit

 int DangerousMethod() { throw WindowsAPI::WindowsException::Create(GetLastError()); } 

For

 int DangerousMethod() { WindowsAPI::WindowsException::Throw(GetLastError()); } 

Instead of throwing an exception and then throwing it (which will cut, as you noticed), use the helper / factory method.

+12
source share

Some more examples of handling exception handling: http://www.informit.com/articles/article.aspx?p=373339

Note on slicing and retrieving types:

When rearranging e exceptions, they prefer to write only the throw; instead of throwing e; because the first form always preserves the polymorphism of the restored object.

+2
source share

All Articles