How to Catch a Non-CLS Exception in .NET C#?

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.

  • Within a catch (RuntimeWrappedException e) block. By default, a Visual C# assembly catches non-CLS exceptions as wrapped exceptions. Use this method if you need access to the original exception, which can be accessed through the RuntimeWrappedException.WrappedException property. The procedure later in this topic explains how to catch exceptions in this manner.
  • Within a general catch block (a catch block without an exception type specified) that is put after all other catch blocks. Use this method when you want to perform some action (such as writing to a log file) in response to non-CLS exceptions and you do not need access to the exception information. By default, the common language runtime wraps all exceptions. To disable this behavior, add this assembly-level attribute to your code, typically in the AssemblyInfo.cs file: [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)].

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);
    }
}
C#
Copy

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.

Ebook Download
View all
testing
Read by 48 people
Download Now!
Learn
View all