Object Oriented Programming
Lecture
Error Handling
Techniques for Error Handling
• Abnormal termination
• Graceful termination
• Return error code from a function
• Exception handling
Example – Abnormal Termination
void GetNumbers(int& a, int& b)
{
cout << "Enter two integers"; int main()
cin >> a >> b; {
} int a, b, quot;
for (int i = 0; i < 10; i++)
{
int Quotient(int a, int b) GetNumbers(a, b);
{ quot = Quotient(a, b);
return a / b; OutputQuotient(quot);
} }
return 0;
}
void OutputQuotient(int quo)
{
cout << "Quotient is " << quo << endl;
}
Output
Enter two integers
10
10
Quotient is 1
Enter two integers
10
0
Program terminated abnormally
Graceful Termination
• Program can be designed in such a way that instead of abnormal
termination, that causes the wastage of resources, program performs
clean up tasks
Example – Graceful Termination
void GetNumbers(int& a, int& b) {
cout << "Enter two integers";
cin >> a >> b;
} int main() {
int a, b, quot;
int Quotient(int a, int b) { for (int i = 0; i < 10; i++)
if (b == 0) {
{ GetNumbers(a, b);
cout << "Denominator can’t be zero" << endl; quot = Quotient(a, b);
exit(1); OutputQuotient(a, b, quot);
} }
return a / b; return 0;
} }
void OutputQuotient(int a, int b, int quo) {
cout << "Quotient is " << quo << endl;
}
Output
Enter two integers
10
10
Quotient is 1
Enter two integers
10
0
Denominator can’t be zero
Return Error Code
• Programmer has avoided the system crash but the program is no
longer running.
• Solution-> Return Error Code
Example – Return Error Code
void GetNumbers(int& a, int& b) {
int main() {
cout << "Enter two integers";
int a, b, quot;
cin >> a >> b;
for (int i = 0; i < 10; i++)
}
{
GetNumbers(a, b);
bool Quotient(int a, int b, int& retVal) {
while (!Quotient(a, b, quot)) {
if (b == 0) {
cout << “Denominator can’t be zero. Give
return false;
input again";
}
GetNumbers(a, b);
retVal = a / b;
}
return true;
}
OutputQuotient(a, b, quot);
}
void OutputQuotient(int a, int b, int quo) {
return 0;
cout << "Quotient is " << quo << endl;
}
}
Output
Enter two integers
10
0
Denominator can’t be zero. Give input again
Enter two integers
10
10
Quotient is 1
Thanks a lot