// exceptions.cpp : Defines the entry point for the console application.
//

#define _CRT_SECURE_NO_WARNINGS	1

#include "stdafx.h"
#include 
#include 
#include 

using namespace std;

class Exception { 
protected:
	char *message;
	int code; 
public:	
	virtual char* msg() {
		return message;
	};
};

class DivisionByZero : 
	public Exception {
public:	
	DivisionByZero() {
		message = "division by zero";
	};
};

class TimestampedException : 
	public Exception {
		time_t when;

public:	
	TimestampedException(const char* m) {
		message = new char[strlen(m)+1];
		strcpy(message, m);

		when = time(NULL);
	};

	char* getwhen() { 
		tm* time_detail = localtime(&when);
		return asctime(time_detail);
	}
};

class AntoherException : 
	public Exception {
public :
	AntoherException() {
		message = "another general exception";
	}
};

int main()  {
	int a = 20;
	int b = 2;
	b--;

	// i say that a should be greater than 20
	// otherwise - print error message
	assert( a > 20 );

	try {
		cout << "Try division ... " << endl;
		if  ( b==0 ) 
		// will be handled by catch(DivisionByZero *e)
			throw new DivisionByZero();
		else
			cout << a / b << endl;

		// will be handled by catch(Exception *e) which is generic for all 
		// Exception-based exceptions

		try {
			// through exception from inner try 

			// will be handled by catch(Exception *e) which is generic for all 
			// Exception-based exceptions
			throw new AntoherException();
		} catch (int) {
			// dummy catch block
		};

		// will be handled by catch(TimestampedException *e)
		throw new TimestampedException("some error");	
	
	} catch(DivisionByZero *e) {
		cout << "Division by zero. Code : " << e->msg() << endl;

	} catch(TimestampedException *e)  {
		cout << "Code : " << e->msg() << endl;
		cout << "Exception generated at : " << e->getwhen() << endl;
	} catch(Exception *e) {
		cout << "General exception : " << e->msg() << endl;
	} 

	return 0;
}


Last modified: Friday, 14 June 2013, 10:44 AM