Exception Handling Andy Wang Object Oriented Programming in

  • Slides: 18
Download presentation
Exception Handling 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

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

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

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 Consists of keyword try

How? Reserved words in C++: try throw, catch try 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

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>

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 some. Function throw (Divide. By. Zero, Other. Exception); This can be used to limit the type of exceptions that a function is allowed to throw

How? void some. Function 1() throw(); // empty throw list void some. Function 2();

How? void some. Function 1() throw(); // empty throw list void some. Function 2(); // 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/cop 3330/examples/exc eptions/except. cpp

Simple Example http: //www. cs. fsu. edu/~myers/cop 3330/examples/exc eptions/except. cpp

Main. cpp #include <iostream> using namespace std; int main() { int cookies, people; double

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 = cookies/static_cast<double>(people); cout << cookies << “ cookies. n” << people <<

Main. cpp = cookies/static_cast<double>(people); cout << cookies << “ cookies. n” << people << “ people. n” << “You have “ << cpp << “ cookies person. n”; } catch(int e) { cout << e << “ people, and no cookies!n. Go 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/savitch 3 c++/Ch 18/1804. cpp

Negative Number Example http: //www. cs. fsu. edu/~myers/savitch 3 c++/Ch 18/1804. cpp

18 -04. cpp #include <iostream> #include <string> using namespace std; class Negative. Number {

18 -04. cpp #include <iostream> #include <string> using namespace std; class Negative. Number { public: Negative. Number() {} Negative. Number(string m): message(m) {} string get. Message() const ( return message; } private: string message; }; class Divide. By. Zero {};

18 -04. cpp int main() { int pencils, erasers; double ppe; try { cout

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 Negative. Number(“pencils”); cout << “How many erasers do you have? n”; cin >> erasers; if (erasers < 0) throw Negative. Number(“erasers”); if (erasers != 0) ppe = pensils/static_cast<double>(erasers); else throw Divide. By. Zero();

18 -04. cpp cout << “Each eraser must last through “ << ppe <<

18 -04. cpp cout << “Each eraser must last through “ << ppe << pencils. n”; } catch(Negative. Number e) { cout << “Cannot have a negative number of “ << e. get. Message() << endl; } catch(Divide. By. Zero) { cout << “Do not make any mistakes. n”; } cout << “End of program. n”; return 0; }

Safe Divide Example http: //www. cs. fsu. edu/~myers/savitch 3 c++/Ch 18/1805. cpp

Safe Divide Example http: //www. cs. fsu. edu/~myers/savitch 3 c++/Ch 18/1805. cpp

18 -05. cpp #include <iostream> #include <cstdlib> using namespace std; class Divide. By. Zero

18 -05. cpp #include <iostream> #include <cstdlib> using namespace std; class Divide. By. Zero {}; double safe. Devide(int top, int bottom) throw (Divide. By. Zero) { if (bottom == 0) thorw Divide. By. Zero(); return top/static_cast<double>(bottom); }

18 -05. cpp int main() { int numerator, denominator; double quotient; cout << “Enter

18 -05. cpp int main() { int numerator, denominator; double quotient; cout << “Enter numerator: n”; cin >> numerator; cout << “Enter denominator: n”; cin >> denominator; try { quotient = safe. Divide(numerator, denominator); } catch(Divide. By. Zero) { cout << “Error: Division by zero!n”; << “Program aborting. n”; exit(0); } cout << numerator << “/” << denominator << “ = “ << quotient << endl; return 0; }