With exception handling -
Programmer can trap exceptions, prevent crashes and freezes and control
what happens next
Basic Concepts
Many languages allow programs to trap input/output errors (including EOF)
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*
User-defined Exception Handling
A language that does not have exception handling built-in can still
define, detect, raise, and handle exceptions
Pass an argument (flag or error msg) to an error-handling routing
or return a flag (boolean, int)
Have some mechanism for interpreting what the return flag means (see
Unix strcmp)
Give exception handling utilities global scope
Advantages of Built-in Exception Handling in C++
Added to C++ in 1990 (Design based on CLU, Ada, and ML)
Code reusability, uniformity, promotes readability
Error detection code is tedious to write and clutters the program
Allows you to rethrow back to main, unwind the runtime stack and perform
cleanup (very difficult to code otherwise)
Saves the return value for something other than error handling
Supports dynamic memory management if objects are allocated in a try block
since destructors are called upon exiting the block
Increases chances that a program can recover without a complete crash
Things you should know about exception handling in any language
Where does execution continue, if at all, after an exception handler
completes its execution?
Exception Handling in C++
Basic syntax:
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: