C.2
Exception Handling Using Try,
Throw, and Catch
Together these three commands provide an easy way to control how the program will execute when an error occurs. The try command is used to encompass the block of code that may generate an error. If an error has been detected the command throw may be used to raise an exception. After the exception has been raised, all code within the try block is then skipped the and an appropriate catch block of code is executed. If no errors occur within the try block program execution continues after the catch block. The three commands are usually found in the following form:
try
{
//code that an error may occur
//an error has been found so raise an exception
throw anobject();
}
catch ( anobject name )
{
//error handling code
}
To better understand try, throw, and catch an example is provided to show how to catch and handle divide by zero. The example uses the object DivZero to capture information about the error that has occurred. If the numerator is equal to zero, the throw command calls the DivZero constructor and creates the DivZero object that is then caught by the catch block. The programmer then has control over the error which occurred, and in this case returns one to show that an error occurred.
#include <iostream.h>
class DivZero
{
public:
DivZero() : ErrorMessage("Divide by zero has occurred. Program terminated.") {}
void theMessage() :
{
cerr<<ErrorMessage;
}
private:
char *ErrorMessage;
}
main ()
{
float number, denom;
cout<<"Enter the numerator: ";
cin>>numer;
cout<<"Enter the denominator: ";
cin>>denom;
try
{
if(denom == 0) throw DivZero();
cout << numer <<" / "<< denom << " = " << numer/denom;
}
catch (DivZero myError)
{
myError.theMessage();
return 1;
}
return 0;
}