Objective: to correctly understand the Exception Handling Mechanism of C ++
Learning the definition and execution process of Exception Handling
Content: defines a cexception class, with a member function reason (), used to display the exception type, trigger an exception in the subfunction, and handle the exception in the main program, observe the execution process of the program.
3. Experiment task: Use cout to display the exception type in the member function reason () of the cexception class, and use throw to trigger the exception in the function fn1, call fn1 () in the try template of the main function to catch exceptions in the catch template.
Algorithm:
Define a class cexception as required, and then have the member function reason () to display the error information. Then define a function to complete the Division function. The trigger condition is Division 0, then define the main function to handle exceptions.
Program:
# Include <iostream. h>
Class cexception
{
PRIVATE:
Int dividend;
Int divisor;
Public:
Void reason () {cout <"0 cannot perform divisor! "<Endl ;}
};
Float fn1 (INT dividend, int divisor)
{
If (divisor = 0)
Throw "error! ";
Else
Return float (dividend)/divisor;
}
Void main ()
{
Cexception object;
Int dividend, divisor;
Float quotient;
Cout <"Enter the divisor and divisor :";
Cin> dividend> divisor;
Try {
Quotient = fn1 (dividend, divisor );
Cout <"OPERATOR:" <quotient <Endl;
} Catch (char * exceptionstring)
{Cout <predictionstring <Endl;
Object. Reason ();
}
}
Article Source: http://www.diybl.com/course/3_program/c++/cppxl/2008215/99845.html