Visual C++ .NET/Statement/throw — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 18:31, 26 мая 2010

Rethrow Exception

<source lang="csharp">

  1. include "stdafx.h"

using namespace System; void main(){

   try{
       try{
           throw gcnew ApplicationException("\t***Boom***");
           Console::WriteLine("Imbedded Try End");
       }catch (ApplicationException ^ie){
           Console::WriteLine("Caught Exception ");
           Console::WriteLine(ie->Message);
           throw;
       }
       Console::WriteLine("Outer Try End");
   }
   catch (ApplicationException ^oe)
   {
       Console::WriteLine("Recaught Exception ");
       Console::WriteLine(oe->Message);
   }

}

 </source>


Throw Derived Exception

<source lang="csharp">

  1. include "stdafx.h"

using namespace System; ref class MyException : public ApplicationException { public:

   MyException( String ^err ); 

}; MyException::MyException(System::String ^err) : ApplicationException(err) { } void main(){

   for (int i = 0; i < 3; i++){
       try{
           if (i == 0){
               Console::WriteLine("\tCounter equal to 0");
           }
           else if (i == 1)
           {
               throw gcnew MyException("\t**Exception** Counter equal to 1");
           }
           else
           {
               Console::WriteLine("\tCounter greater than 1");
           }
       }
       catch (MyException ^e)
       {
           Console::WriteLine(e->Message);
       }
   }

}

 </source>


Throw gcnew exception

<source lang="csharp">

  1. include "stdafx.h"

using namespace System; int main() { try {

    bool error = true;
    // other code
    if (error)
    {
         throw gcnew Exception();
    }

} catch( Exception^ exception) {

     // code to handle the exception

} }

 </source>


Throw string as exception

<source lang="csharp">

  1. include "stdafx.h"

using namespace System; public ref class MyClass { public:

  static void TrySomething()
  {
     throw gcnew String("Error that throws string!");
  }

}; int main() {

  try
  {
     MyClass::TrySomething();
  }
  catch(String^ s)
  {
     Console::WriteLine(s);
  }

}

 </source>