Docsity

Techniques for Error Handling - Object Oriented Programming - Lecture Slides, Slides of Object Oriented Programming

Partial preview of the text

Download Techniques for Error Handling - Object Oriented Programming - Lecture Slides and more Slides Object Oriented Programming in PDF only on Docsity!

Object-Oriented Programming

(OOP)

Lecture No. 43

Techniques for Error Handling

  • Abnormal termination
  • Graceful termination
  • Return the illegal value
  • Return error code from a function
  • Exception handling

Example – Abnormal

Termination

int main(){ int sum = 0, quot; int a, b; for (int i = 0; i < 10; i++){ GetNumbers(a,b); quot = Quotient(a,b); sum += quot; OutputQuotient(a,b,quot); } cout << “\nSum of ten quotients is ”<< sum; return 0; }

Output

Enter two integers

10

10

Quotient of 10 and 10 is 1

Enter two integers

10

0

Program terminated abnormally

Example – Graceful Termination

int Quotient (int a, int b ) { if(b == 0){ cout << “Denominator can’t “ << “ be zero” << endl; // Do local clean up exit(1); } return a / b; }

Output

Enter two integers

10

10

Quotient of 10 and 10 is 1

Enter two integers

10

0

Denominator can’t be zero

Example – Return Illegal Value

int Quotient(int a, int b){ if(b == 0) b = 1; OutputQuotient(a, b, a/b); return a / b ; } int main() { int a,b,quot; GetNumbers(a,b); quot = Quotient(a,b); return 0; }

Output

Enter two integers

10

0

Quotient of 10 and 1 is 10

Example – Return Error Code

bool Quotient ( int a, int b, int & retVal ) { if(b == 0){ return false; } retVal = a / b; return true; }

Part of main Function

for(int i = 0; i < 10; i++){ GetNumbers(a,b); while (! Quotient(a, b, quot) ) { cout << “Denominator can’t be ” << “Zero. Give input again \n”; GetNumbers(a,b); } sum += quot; OutputQuotient(a, b, quot); }

Error Handling

  • Programmer sometimes has to change the design to incorporate error handling
  • Programmer has to check the return type of the function to know whether an error has occurred

Error Handling

  • Programmer of calling function can ignore the return value
  • The result of the function might contain illegal value, this may cause a system crash later

Example

int main() {

function1(); function2(); function3();

return 0;

}

Example

int main(){ if( function1() ) { if( function2() ) { if( function3() ) { ... } else cout << “Error Z has occurred”; } else cout << “Error Y has occurred”; } else cout << “Error X has occurred”; return 0; }