






















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!























13.2 Exception-Handling Overview
Simple Exception Handler -- Example
An Exception Handler Class -- Example
#include<stream.h> #include<stdlib.h> //exit() class zero{ public: zero() //Constructor {cout<<"Class Zero Constructor Invoked!!"<<endl;} }; //Exception Checker Function void zero_check(int i){ if (i == 0) throw zero(); //Argument is of zero class type.} main(){ //try block try{for (int i = 2; ; i--){ zero_check(i); cout << "Reciprocal: " << 1.0/i << endl;}} //Handler catch(zero) {cout << "DIVIDE BY ZERO -- ERROR!!\n"; exit(-1);} } OUTPUT WILL BE:
Reciprocal: 0. Reciprocal: 1 Class Zero Constructor Invoked!! DIVIDE BY ZERO -- ERROR!!
Simple Exception-Handling Example: Divide by Zero
1 // Fig. 13.1: fig13_01.cpp 2 // A simple exception-handling example that checks for 3 // divide-by-zero exceptions. 4 #include
47 // enable user to enter two integers to divide 48 while ( cin >> number1 >> number2 ) { 49 50 // try block contains code that might throw exception 51 // and code that should not execute if an exception occurs 52 try { 53 result = quotient( number1, number2 ); 54 cout << "The quotient is: " << result << endl; 55 56 } // end try 57 58 // exception handler handles a divide-by-zero exception 59 catch ( DivideByZeroException ÷ByZeroException ) { 60 cout << "Exception occurred: " 61 << divideByZeroException.what() << endl; 62 63 } // end catch 64 65 cout << "\nEnter two integers (end-of-file to end): "; 66 67 } // end while 68 69 cout << endl; 70 71 return 0; // terminate normally 72 73 } // end main
Enter two integers (end-of-file to end): 100 7 The quotient is: 14.
Enter two integers (end-of-file to end): 100 0 Exception occurred: attempted to divide by zero
Enter two integers (end-of-file to end): ^Z
1 // Fig. 13.2: fig13_02.cpp 2 // Demonstrating exception rethrowing. 3 #include
31 cout << "This also should not print\n"; 32 33 } // end function throwException 34 35 int main() 36 { 37 // throw exception 38 try { 39 cout << "\nmain invokes function throwException\n"; 40 throwException(); 41 cout << "This should not print\n"; 42 43 } // end try 44 45 // handle exception 46 catch ( exception &caughtException ) { 47 cout << "\n\nException handled in main\n"; 48 49 } // end catch 50 51 cout << "Program control continues after catch in main\n"; 52 53 return 0; 54 55 } // end main