Visual C++ .NET/Statement/throw
Содержание
Rethrow Exception
#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);
}
}
Throw Derived Exception
#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);
}
}
}
Throw gcnew exception
#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
}
}
Throw string as exception
#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);
}
}