The code below shows how to use try, throw and catch (exception handling). It fairly crude but it does show one way it can be used.
Code:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Exception{
string s;
public:
Exception(string error): s(error){};
friend ostream& operator << (ostream& os, Exception& e)
{
return os << "Exception: " << e.s;
}
};
class CThing
{
int m_thing;
public:
CThing( int n = -1 ) : m_thing( n )
{ }
int GetThing( )
{
return m_thing;
}
void SetThing( int n )
{
m_thing = n;
}
};
string e( "Thing initialize to -1" );
Exception ex( e );
bool GetSomething( CThing & thing );
int main(int argc, char* argv[])
{
bool Cont = true;
CThing tg;
while ( Cont )
{
try
{
Cont = GetSomething( tg );
}
catch ( Exception &exc )
{
cout << exc;
//Correct problem and continue
tg.SetThing( 0 );
}
catch ( ... ) //if you remove the above catch it will use the catch all catch here
{
cout << "Catch anything and avoid the nasty system Exception message" << endl;
}
}
return 0;
}
bool GetSomething( CThing & thing )
{
if( -1 == thing.GetThing( ) )
{
throw ex;
}
cout << "\n\nDid something" << endl << endl;
return false;
}