Пример #1
0
        // 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:
        static void Example7()
        {
            // 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();
            }
            // 1º Within a catch (RuntimeWrappedException e) block.
            catch (RuntimeWrappedException e)
            {
                // 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.
                String s = e.WrappedException as String;
                if (s != null)
                {
                    Console.WriteLine(s);
                }
            }
            // 2º Within a general catch block (a catch block without an exception type specified) that is put after all other catch blocks.
            catch
            {
                // 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)].
            }
        }
Пример #2
0
        static void Main(string[] args)
        {
            // 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);
                }
            }
        }