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 HR
It is possible to catch Exception, handle particular errors by switching on the HRESULT, and re-throwing the Exception if the error was "unexpected." For example,
try
{
// ...
}
catch (Exception ex)
{
switch (ex->HResult)
{
case E_INVALID_USER_BUFFER: // 0x800706f8
// handle invalid buffer case...
break;
default:
// Unexpected exception; re-throw:
throw;
}
}
(I would note that providing an invalid buffer sounds more like a logic error than a runtime error, so I wonder whether this particular exception should really be caught.)
Alternatively, a more general solution would be to write a function or set of functions that handle Exception for known HRESULTs and re-throws a more specific exception. For example,
static void HandleKnownExceptions(Action f)
{
try
{
f();
}
catch (Exception ex)
{
// Detect expected HRESULTs and throw the more-specific exception
// type for each.
}
}
Both of these approaches work equally well in both C++ and C#.
Note that it isn't necessarily the case that Exception is thrown directly by the platform or other components. At the Windows Runtime ABI layer, there are no exceptions: all errors are reported across the ABI boundary by HRESULT. The CLR translates a handful of known HRESULTs to more specific exception types, but it cannot perform a general translation.