Andy Wang Object Oriented Programming in C++ COP 3330 Exception Handling Andy Wang Object Oriented Programming in C++ COP 3330
Exception Handling A type of error checking, available in many programming languages Exception Some sort of problem or error that occurs during a program’s execution Many error situations could occur besides those that we usually check for (usually related to things like user input) Exception handler A piece of code that resolves an exception situation Typical error check often intermixed with the tasks of a program (if statements, etc) Exception handlers are intended to be separate from the main tasks
Why? Intermixing program logic with the error-checking code can sometimes make programs hard to read, debug, etc. Many potential problems are very infrequent Exception handlers are separate from main tasks of a program Can improve clarity and modifiability Exception handling can improve a program’s fault tolerance
When? This does not mean that exception handlers should be used in all cases Sometimes conventional error checking is more appropriate Exception handling best for problems that occur infrequently Errors that will result in termination of the program Not for user input checking Good for setting up uniform techniques for error handling when many programmers and multiple modules are involved
How? Reserved words in C++: try throw, catch try blocks catch blocks Consists of keyword try and a block of code inside { } Encloses the statements that might cause exceptions catch blocks 1+ catch blocks follow a try block (also in { }) Each catch block is an exception handler A cache block has a single parameter (with type listed)
How? If an exception occurs in a try block The try block immediately ends Program attempts to match the exception to one of the catch handlers (based on type of item thrown) If a match is found, the code in the catch block executes Only one catch block will be matched, if any Program control resumes after the last catch block If no exception occur in a try block, the catch blocks are skipped A point where an exception occurs is the throw point Keyword throw used to throw an exception to be caught
How? In C++, there is a standard library with pre-built exception classes #include <exception> using std::exception; When a function intends to throw an exception back to the caller (not handled internally), it’s good to tell the caller what to expect via a throw list when declaring a function void someFunction throw (DivideByZero, OtherException); This can be used to limit the type of exceptions that a function is allowed to throw
How? The first function can throw no exceptions to the outside void someFunction1() throw(); // empty throw list void someFunction2(); // no throw list The first function can throw no exceptions to the outside The second can throw exceptions of any kind
Simple Example http://www.cs.fsu.edu/~myers/cop3330/examples/exc eptions/except.cpp
Main.cpp #include <iostream> using namespace std; int main() { int cookies, people; double cpp; try { cout << “Enter number of people: “; cin >> people; cout << “Enter number of cookies: “; cin >> cookies if (cookies == 0) throw people; if (cookies < 0) throw static_cast<double>(people);
Main.cpp cpp = cookies/static_cast<double>(people); cout << cookies << “ cookies.\n” << people << “ people.\n” << “You have “ << cpp << “ cookies per person.\n”; } catch(int e) { cout << e << “ people, and no cookies!\nGo buy some cookies!\n”; catch(double t) { cout << “Second catch block type double – do we reach it?\n”; cout << “End of program.\n”; return 0;
Negative Number Example http://www.cs.fsu.edu/~myers/savitch3c++/Ch18/18- 04.cpp
18-04.cpp #include <iostream> #include <string> using namespace std; class NegativeNumber { public: NegativeNumber() {} NegativeNumber(string m): message(m) {} string getMessage() const ( return message; } private: string message; }; class DivideByZero {};
18-04.cpp int main() { int pencils, erasers; double ppe; try { cout << “How many pencils do you have?\n”; cin >> pencils; if (pencils < 0) throw NegativeNumber(“pencils”); cout << “How many erasers do you have?\n”; cin >> erasers; if (erasers < 0) throw NegativeNumber(“erasers”); if (erasers != 0) ppe = pensils/static_cast<double>(erasers); else throw DivideByZero();
18-04.cpp cout << “Each eraser must last through “ << ppe << pencils.\n”; } catch(NegativeNumber e) { cout << “Cannot have a negative number of “ << e.getMessage() << endl; catch(DivideByZero) { cout << “Do not make any mistakes.\n”; cout << “End of program.\n”; return 0;
Safe Divide Example http://www.cs.fsu.edu/~myers/savitch3c++/Ch18/18- 05.cpp
18-05.cpp #include <iostream> #include <cstdlib> using namespace std; class DivideByZero {}; double safeDevide(int top, int bottom) throw (DivideByZero) { if (bottom == 0) throw DivideByZero(); return top/static_cast<double>(bottom); }
18-05.cpp int main() { int numerator, denominator; double quotient; cout << “Enter numerator:\n”; cin >> numerator; cout << “Enter denominator:\n”; cin >> denominator; try { quotient = safeDivide(numerator, denominator); } catch(DivideByZero) { cout << “Error: Division by zero!\n”; << “Program aborting.\n”; exit(0); cout << numerator << “/” << denominator << “ = “ << quotient << endl; return 0;