If a Windows runtime type raises a COM error .NET seems to wrap this error often (or always?) just into an Exception
instance. The error message includes the COM HRESULT error code. When using the new Cryptographic API with AES-CBC for example a wrong buffer length results in an Exception
with the message "The supplied user buffer is not valid for the requested operation. (Exception from HRESULT: 0x800706F8
)".
Well, How are we supposed to handle those exceptions? Should we read the HRESULT
code from the exception to get an idea what kind of exception that was? In classic .NET I would get a CryptographicException
that I could use to distinguish cryptographic errors from other errors.
Another thing that I do not understand is that the Microsoft code quality rules state that one should never throw Exception but always derived types. The reason is that no one should be forced to catch the general Exception
that catches more fatal exceptions like OutOfMemoryException
as well. Another rule says that one should never, ever catch Exceptio
n in libraries. How could we follow these policies if we are forced to catch Exception
in Windows Store apps or WinRT libraries?
By the way: Clemens Vasters shows in his blog how we can catch Exception while avoiding to catch fatal exception. I assume catching Exception
is no longer bad code then.
StackOverflowException
, though I'm fairly certain that AVs can't be caught either (both can be caught in native code, of course, but doing so is perilous). Note also that some exceptions that appear fatal may not in fact be so. For example, many COM components returnE_OUTOFMEMORY
when space in a particular buffer is exhausted. This HRESULT will be translated as an OutOfMemoryException, but it doesn't mean that the process has exhausted its entire address space. – Colchester