Exceptions An exception is an object that stores information transmitted outside the normal return sequence. It is propagated back through calling stack until some function catches it. If no calling function catches the exception, the program terminates. Why? Exceptions are anomalies that occur during the normal flow of a program and prevent it from continuing. These anomalies--user, logic, or system errors--can be detected by a function. If the detecting function cannot deal with the anomaly, it throws, an exception. A function that handles that kind of exception catches it. In C++, when an exception is thrown, it cannot be ignored--there must be some kind of notification or termination of the program. If no user-provided exception handler is present, the compiler provides a default mechanism to terminate the program. Exception handling is expensive compared to ordinary program flow controls, such as loops or if-statements. It is therefore better not to use the exception mechanism to deal with ordinary situations, but to reserve it for situations that are truly unusual. For example, a function might have the job of opening a file and initializing some associated data. If the file cannot be opened or is corrupted, the function cannot do its job. However, that function might not have enough information to handle the problem. The function can throw an exception object that describes the problem, transferring control to an earlier point in the program. The exception handler might automatically try a backup file, query the user for another file to try, or shut down the program gracefully. Without exception handlers, status and data would have to be passed down and up the function call hierarchy, with status checks after every function call. With exception handlers, the flow of control is not obscured by error checking. If a function returns, the caller can be certain that it succeeded. Fall 2018 Husain Gholoom Lecturer in Computer Science Page 1
Using ( try catch ) There are three keywords for exception handling in C++: try throw catch try A try block is a group of C++ statements, normally enclosed in braces, which may cause an exception. This grouping restricts exception handlers to exceptions generated within the try block. throw The throw statement is used to throw an exception to a subsequent exception handler. A throw statement is specified with: The keyword throw. An assignment expression; the type of the result of the expression determines which catch exception handler receives control catch A catch block is a group of C++ statements that are used to handle a specific raised exception. Catch blocks, or handlers, should be placed after each try block. A catch block is specified by: The keyword catch A catch expression, which corresponds to a specific type of exception that may be thrown by the try block A group of statements, enclosed in braces, whose purpose is to handle the exception Fall 2018 Husain Gholoom Lecturer in Computer Science Page 2
Example - 1 double division(int a, int b) if (b == 0) throw "Division by zero condition!"; return (a / b); int main() int x = 50; int y = 0; double z = 0; try z = division(x, y); cout << z << endl; catch (const char* msg) cout << msg << endl; Division by zero condition! Fall 2018 Husain Gholoom Lecturer in Computer Science Page 3
Example 2 int main() int x = - 1; // Some code cout << "Before try \n"; try cout << "Inside try \n"; if (x < 0) throw x; cout << "After throw (Never executed) \n"; catch (int x ) cout << "Exception Caught \n"; cout << "After catch (Will be executed) \n"; Before try Inside try Exception Caught After catch (Will be executed) Fall 2018 Husain Gholoom Lecturer in Computer Science Page 4
There is a special catch block called catch all catch( ) that can be used to catch all types of exceptions. For example, in the following program, an int is thrown as an exception, but there is no catch block for int, so catch( ) block will be executed Example 3 int main() try throw "a"; catch (char *exception) cout << "Caught " << exception; catch (...) cout << "Default Exception\n"; Caught a Fall 2018 Husain Gholoom Lecturer in Computer Science Page 5
Example 4 int main() try throw 10; catch (char *exception) cout << "Caught " << exception; catch (...) cout << "Default Exception\n"; Default Exception Fall 2018 Husain Gholoom Lecturer in Computer Science Page 6
Implicit type conversion doesn t happen for primitive types. For example, in the following program a is not implicitly converted to int Example 5 int main() try throw 'a'; catch (int x) cout << "Caught " << x; catch (...) cout << "Default Exception\n"; Default Exception Fall 2018 Husain Gholoom Lecturer in Computer Science Page 7
If an exception is thrown and not caught anywhere, the program terminates abnormally. For example, in the following program, a char is thrown, but there is no catch block to catch a char. Example 6 int main() try throw 'a'; catch (int x) cout << "Caught "; terminate called after throwing an instance of 'char' 0 [main] trycatchexample 5704 cygwin_exception::open_stackdumpfile: Dumping stack trace to trycatchexample.exe.stackdump Fall 2018 Husain Gholoom Lecturer in Computer Science Page 8
Dynamic Allocation Example 7 int main () try char * mystring; mystring = new char [10]; if (mystring == NULL) throw "Allocation failure"; for (int n=0; n<=100; n++) if (n>9) throw n; mystring[n]='z'; cout << mystring[n] << " "; catch (int i) cout << "\n\nexception: "; cout << "index " << i << " is out of range" << endl; catch (char * str) cout << "\n\nexception: " << str << endl; z z z z z z z z z z Exception: index 10 is out of range Fall 2018 Husain Gholoom Lecturer in Computer Science Page 9
Example 8 int main () try char * mystring; mystring = NULL; if (mystring == NULL) throw "Allocation failure"; for (int n=0; n<=100; n++) if (n>9) throw n; mystring[n]='z'; cout << mystring[n] << " "; catch (int i) cout << "\n\nexception: "; cout << "index " << i << " is out of range" << endl; catch (char * str) cout << "\n\nexception: " << str << endl; Exception: Allocation failure Fall 2018 Husain Gholoom Lecturer in Computer Science Page 10
What is the output of the following program #include<iostream> int main() try throw(55.5); throw('i'); catch (int e) cout << "Input is Integer value " << e << endl; catch (double e) cout << "Input is Double value " << e << endl; catch (char e) cout << "Input is Character " << e << endl; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 11
in Vectors - 1 #include <vector> int main() /* Initialize vector of 10 copies of the integer 5 */ vector<int> vectorone(10,5); cout<< "Display elements of vector - unsafe code " << endl << endl; for (int index=0; index< 15; ++index) cout << vectorone[index] << " " ; return EXIT_SUCCESS; Display elements of vector - unsafe code 5 5 5 5 5 5 5 5 5 5 0 51 1629486856-552734650 537269376 Fall 2018 Husain Gholoom Lecturer in Computer Science Page 12
in Vectors - 2 #include <vector> int main() /* Initialize vector of 10 copies of the integer 5 */ vector<int> vectorone(10,5); cout<< "Display elements of vector - unsafe code - runtime error " << endl << endl; for (long index=0; index<20; ++index) cout << "Element " << index << ": " << vectorone.at(index) << endl; cout<<endl<<endl; Display elements of vector - unsafe code - runtime error Element 0: 5 Element 1: 5 Element 2: 5 Element 3: 5 Element 4: 5 Element 5: 5 Element 6: 5 Element 7: 5 Element 8: 5 Element 9: 5 terminate called after throwing an instance of 'std::out_of_range' what(): vector::_m_range_check 0 [main] trycatchexample 552 cygwin_exception::open_stackdumpfile: Dumping stack trace to trycatchexample.exe.stackdump Fall 2018 Husain Gholoom Lecturer in Computer Science Page 13
in Vectors - 3 #include <vector> int main() /* Initialize vector of 10 copies of the integer 5 */ vector<int> vectorone(10,5); cout<< "Display the elements of vector - safe code " << endl << endl; // run through the vector and display each element, if possible for (long index=0; index<20; ++index) try cout << "Element " << index << ": " << vectorone.at(index) << endl; catch (exception& e) cout << "Element " << index << ": index exceeds vector dimensions." << endl; return 0 ; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 14
Display the elements of vector - safe code Element 0: 5 Element 1: 5 Element 2: 5 Element 3: 5 Element 4: 5 Element 5: 5 Element 6: 5 Element 7: 5 Element 8: 5 Element 9: 5 Element 10: index exceeds vector dimensions. Element 11: index exceeds vector dimensions. Element 12: index exceeds vector dimensions. Element 13: index exceeds vector dimensions. Element 14: index exceeds vector dimensions. Fall 2018 Husain Gholoom Lecturer in Computer Science Page 15