An exception is any unusual event, either erroneous or not, detectable by either hardware or software, that may cause a crash or freeze if not otherwise handled
Most common Examples: divide by zero, illegal memory access (dereferencing a bad pointer, array out-of-bounds), file open errors, input errors (reading float into char), reading past EOF
Processing the exception is called *exception handling*
An exception is *raised* when its associated event occurs The exception handling code unit is called an *exception handler*
try {
throw
}
catch (formal parameter) {
throw // optional re-throw will propogate through runtime state
}
catch (...) { // a generic handler
}
Specific example:
const int DivideByZero = 10;
//....
double divide(double x, double y) {
if(y==0) throw DivideByZero;
return x/y;
}
///...
try {
divide(10, 0);
}
catch(int i) {
if (i==DivideByZero) cerr << "Divide by zero error";
}
// example of error objects
class DivideByZero
{
public:
double divisor;
DivideByZero(double x);
};
DivideByZero::DivideByZero(double x) : divisor(x)
{}
int divide(int x, int y)
{
if(y==0)
{
throw DivideByZero(x);
}
}
try
{
divide(12, 0);
}
catch (DivideByZero divZero)
{
cerr<<"Attempted to divide "<<divZero.divisor<<" by zero";
}
Notes on C++ facility: