Export (0) Print
Expand All

How to: Catch a non-CLS Exception



    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 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 a catch (Exception) or catch (Exception e) block.

    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


  2. Access the original exception through the WrappedException property.


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

    // throws gcnew System::String(

   catch (Exception e)
    RuntimeWrappedException rwe = e as RuntimeWrappedException;
    if (rwe != null)    
      String s = rwe.WrappedException as String;
      if (s != null)
       // Handle other System.Exception types.

Community Additions

© 2014 Microsoft