c++ - Exceptions (Source)
Header
except.h
#ifndef EXCEPT_H
#define EXCEPT_H
#include <exception>
#include <string>
class FruitException: public std::exception
{
public:
FruitException();
virtual ~FruitException() throw();
virtual const char *what() const throw();
protected:
std::string sWhat;
};
class AppleException: public FruitException
{
public:
AppleException(std::string sDetail);
virtual ~AppleException() throw();
};
class BananaException: public FruitException
{
public:
BananaException(std::string sDetail);
virtual ~BananaException() throw();
};
#endif
Source
except.cpp
#include "except.h"
#include <iostream>
FruitException::FruitException():
sWhat("FruitException")
{
}
FruitException::~FruitException() throw()
{
}
const char *FruitException::what() const throw()
{
return sWhat.c_str();
}
AppleException::AppleException(std::string sDetail)
{
sWhat += ": Apples are ";
sWhat += sDetail;
}
AppleException::~AppleException() throw()
{
}
BananaException::BananaException(std::string sDetail)
{
sWhat += ": Bananas are ";
sWhat += sDetail;
}
BananaException::~BananaException() throw()
{
}
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;
}