What happens when your managed .NET code interacts with legacy libraries that are .NET agnostic. In general cases, when you interact with unmanaged code using the Platform Invoke (P/Invoke) or COM Interoperability mechanisms provided by the .NET framework, an exception raised from unmanaged code would be mapped back by the CLR into an appropriate .NET exception type. However, there are cases where legacy unmanaged libraries could possibly raise exceptions that are not System.Exception compliant, which cannot be mapped to a corresponding .NET exception type. In such cases, you can use a generic exception handler that can catch errors that are not .NET aware and not compliant with System.Exception. The generic catch handler contains only the catch keyword and does not specify an exception type filter. Here’s an example code snippet with a generic catch handler:
Code listing in C#
try
{
// This is the try block
}
catch(Exception ex)
{
// This is the catch block to handle System.Exception errors
}
catch
{
// This is a generic catch block to handle calls to libraries that raise
// exceptions which are not compliant with System.Exception. Can catch
// any error that the other catch handlers cannot handle.
}
finally
{
// This is the finally block
}
Code listing in VB.NET
Try
' This is the Try block
Catch ex As Exception
' This is the catch block to handle System.Exception errors
Catch
' This is a generic catch block to handle calls to libraries that raise
' exceptions which are not compliant with System.Exception. Can catch
' any error that the other catch handlers cannot handle.
Finally
' This is the finally block
End Try