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 programs execution ID: 538931
Download Presentation The PPT/PDF document "Exception Handling" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Exception Handling
Andy Wang
Object Oriented Programming in C++
COP 3330Slide2
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 tasksSlide3
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 toleranceSlide4
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 involvedSlide5
How?
Reserved words in C++: try throw, catch
t
ry
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)Slide6
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 caughtSlide7
How?
In C++, there is a standard library with pre-built exception classes
#include <exception>
u
sing
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
v
oid
someFunction
throw (
DivideByZero
,
OtherException
);
This can be used to
limit the type of exceptions that a function is allowed to throwSlide8
How?
v
oid someFunction1() throw(); // empty throw list
v
oid someFunction2(); // no throw list
The first function can throw no exceptions to the outside
The second can throw exceptions of any kindSlide9
Simple Example
http://www.cs.fsu.edu/~myers/cop3330/examples/exceptions/except.cppSlide10
Main.cpp
#include <
iostream
>
u
sing namespace
std
;
i
nt
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);Slide11
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;
}Slide12
Negative Number Example
http://www.cs.fsu.edu/~myers/savitch3c++/Ch18/18-04.cppSlide13
18-04.cpp
#include <
iostream
>
#include <string>
u
sing namespace
std
;
c
lass
NegativeNumber
{
public:
NegativeNumber
() {}
NegativeNumber
(string m): message(m) {}
string
getMessage
()
const
( return message; }
private:
string message;
};
c
lass
DivideByZero
{};Slide14
18-04.cpp
i
nt
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
();Slide15
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;
}Slide16
Safe Divide Example
http://www.cs.fsu.edu/~myers/savitch3c++/Ch18/18-05.cppSlide17
18-05.cpp
#include <
iostream
>
#include <
cstdlib
>
u
sing namespace
std
;
c
lass
DivideByZero
{};
double
safeDevide
(
int
top,
int
bottom) throw (
DivideByZero
) {
if (bottom == 0)
thorw
DivideByZero
();
return top/
static_cast
<double>(bottom);
}Slide18
18-05.cpp
i
nt
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;
}