tutorials.neonphog.com icon

c++ - Exceptions (Source)

Header Source

Header

except.h

#ifndef EXCEPT_H
#define EXCEPT_H

#include <exception>
#include <string>

//FruitException Base Class
class FruitException: public std::exception
{
public:
	FruitException();
	virtual ~FruitException() throw();
	virtual const char *what() const throw();

protected:
	std::string sWhat;
};

//AppleException
class AppleException: public FruitException
{
public:
	AppleException(std::string sDetail);
	virtual ~AppleException() throw();
};

//BananaException
class BananaException: public FruitException
{
public:
	BananaException(std::string sDetail);
	virtual ~BananaException() throw();
};

#endif

Source

except.cpp

#include "except.h"

#include <iostream>

//Begin FruitException Code
FruitException::FruitException():
	sWhat("FruitException")
{
}

FruitException::~FruitException() throw()
{
}

const char *FruitException::what() const throw()
{
	return sWhat.c_str();
}
//End FruitException Code


//Begin AppleException Code
AppleException::AppleException(std::string sDetail)
{
	sWhat += ": Apples are ";
	sWhat += sDetail;
}

AppleException::~AppleException() throw()
{
}
//End AppleException Code


//Begin BananaException Code
BananaException::BananaException(std::string sDetail)
{
	sWhat += ": Bananas are ";
	sWhat += sDetail;
}

BananaException::~BananaException() throw()
{
}
//End BananaException Code


void testExcept(int iMode)
{
	std::cout << std::dec << iMode << ": ";
	try
	{
		switch( iMode )
		{
			case 0:
				throw FruitException();
				break;
			case 1:
				throw AppleException("rotten");
				break;
			case 2:
				throw BananaException("getting brown");
				break;
			default:
				std::cout << "Got away clean!" << std::endl;
				break;
		}
	}
	catch( AppleException &e )
	{
		std::cout << "Caught an AppleException: " << std::endl;
		std::cout << "\t" << e.what() << std::endl;
	}
	catch( FruitException &e )
	{
		std::cout << "Caught a basic FruitException: " << std::endl;
		std::cout << "\t" << e.what() << std::endl;
	}
}

int main()
{
	for( int i=0; i<4; ++i )
	{
		testExcept(i);
	}
	return 0;
}
tutorials home c++ home