Introduction

Some .NET languages, including C++/CLI, allow objects to throw exceptions that do not derive from Exception. Such exceptions are called non-CLS exceptions or non-Exceptions. In C#, you cannot throw non-CLS exceptions,

but you can catch them in two ways.

To catch a non-CLS exception

Within a catch(RuntimeWrappedException e) block, access the original exception through the RuntimeWrappedException.WrappedException property.

Example

The following example shows how to catch a non-CLS exception that was thrown from a class library written in C++/CLI.

Note. that in this example, the C# client code knows in advance that the exception type being thrown is a System.String. You can cast the RuntimeWrappedException.WrappedException property back to its original type as long as that type is accessible from your code.

// Class library written in C++/CLI.
var myClass = new ThrowNonCLS.Class1();

try
{
    // throws gcnew System::String(  
    // "I do not derive from System.Exception!");  
    myClass.TestThrow();
}
catch (RuntimeWrappedException e)
{
    String s = e.WrappedException as String;
    if (s != null)
    {
        Console.WriteLine(s);
    }
}

Conclusion

By catching the base Exception class, you catch all exceptions, whether they are CLS-compliant or not. However, it's important to note that handling non-CLS exceptions might not be straightforward because they might be specific to certain. This way, you can handle exceptions from non-CLS-compliant assemblies in your managed code. However, it's generally recommended to minimize the use of non-CLS-compliant exceptions for better interoperability between different .NET languages and platforms.