Publications: 83 | Followers: 0

Exception Handling - Florida State University

Publish on Category: Birds 0

Exception Handling
Andy WangObject Oriented Programming in C++COP 3330
Exception Handling
A type of error checking, available in many programming languagesExceptionSome sort of problem or error that occurs during a program’s executionMany error situations could occur besides those that we usually check for (usually related to things like user input)Exception handlerA piece of code that resolves an exception situationTypical 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 infrequentException handlers are separate from main tasks of a programCan improve clarity and modifiabilityException handling can improve a program’s fault tolerance
When?
This does not mean that exception handlers should be used in all casesSometimes conventional error checking is more appropriateException handling best for problems that occur infrequentlyErrors that will result in termination of the programNot for user input checkingGood for setting up uniform techniques for error handling when many programmers and multiple modules are involved
How?
Reserved words in C++: try throw, catchtryblocksConsists of keyword try and a block of code inside { }Encloses the statements that might cause exceptionscatchblocks1+ catch blocks follow a try block (also in { })Each catch block is an exception handlerA cache block has a single parameter (with type listed)
How?
If an exception occurs in a try blockThe try block immediately endsProgram 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 executesOnly one catch block will be matched, if anyProgram control resumes after the last catch blockIf no exception occur in a try block, the catch blocks are skippedA point where an exception occurs is the throw pointKeyword throw used to throw an exception to be caught
How?
In C++, there is a standard library with pre-built exception classes#include <exception>usingstd::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 athrow listwhen declaring a functionvoidsomeFunctionthrow (DivideByZero,OtherException);This can be used tolimit the type of exceptions that a function is allowed to throw
How?
void someFunction1() throw(); // empty throw listvoid someFunction2(); // no throw listThe first function can throw no exceptions to the outsideThe second can throw exceptions of any kind
Simple Example
http://www.cs.fsu.edu/~myers/cop3330/examples/exceptions/except.cpp
Main.cpp
#include <iostream>using namespacestd;intmain() {intcookies, people;doublecpp;try {cout<< “Enter number of people: “;cin>> people;cout<< “Enter number of cookies: “;cin>> cookiesif (cookies == 0) throw people;if (cookies < 0) throwstatic_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(inte) {cout<< e << “ people, and no cookies!\nGobuy 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 namespacestd;classNegativeNumber{public:NegativeNumber() {}NegativeNumber(string m): message(m) {}stringgetMessage()const( return message; }private:string message;};classDivideByZero{};
18-04.cpp
intmain() {intpencils, erasers;doubleppe;try {cout<< “How many pencils do you have?\n”;cin>> pencils;if (pencils < 0) throwNegativeNumber(“pencils”);cout<< “How many erasers do you have?\n”;cin>> erasers;if (erasers < 0) throwNegativeNumber(“erasers”);if (erasers != 0)ppe=pensils/static_cast<double>(erasers);elsethrowDivideByZero();
18-04.cpp
cout<< “Each eraser must last through “ <<ppe<< pencils.\n”;}catch(NegativeNumbere) {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 namespacestd;classDivideByZero{};doublesafeDevide(inttop,intbottom) throw (DivideByZero) {if (bottom == 0)throwDivideByZero();return top/static_cast<double>(bottom);}
18-05.cpp
intmain() {intnumerator, 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;}

0

Embed

Share

Upload

Make amazing presentation for free
Exception Handling - Florida State University