Exceptions in C++
An Introduction
|
Prof. David Bernstein
James Madison University
|
|
Computer Science Department
|
bernstdh@jmu.edu
|
Motivation
- The Problem:
- Your method can't handle the values its been given
- One Example:
- A calculation that results in a negative price
- One Solution:
Questions and Observations
- A Question:
-
What "special value" would you return for a method that
fails while converting a string into a
double
?
- Some Observations:
-
It is not always applicable to return a "special value"!
-
It would be nice to have an alternative return mechanism.
The try-catch
Statement
- Normal Return:
- When things work "normally", control is returned to the line
after the function call (in the
try
block)
- Exceptional Return:
- When things work "abnormally", control is
returned to the appropriate
catch
block
The try-catch
Statement (cont.)
- Syntax:
-
try {statement}
catch(exception
name) {[statement;]...}
- An Example:
The try-catch
Statement (cont.)
Writing an Exception Class - The Specification
cppexamples/exceptions/NumberFormatException.h
The try-catch
Statement (cont.)
Writing an Exception Class - The Implementation
cppexamples/exceptions/NumberFormatException.cpp
The try-catch
Statement (cont.)
Using an Exception Class in Another Class - The Specification
cppexamples/exceptions/StringConverter.h
The try-catch
Statement (cont.)
Using an Exception Class in Another Class - The Implementation
cppexamples/exceptions/StringConverter.cpp
The try-catch
Statement (cont.)
Using an Exception Class- Use
cppexamples/exceptions/Driver.cpp
Overuse
- Use exception handling judiciously
- Don't use exception handling where other
techniques can be applied easily (e.g., accessing
a non-existent element of an array)
Standardization
- A Convenient Base Class:
- The C++ Standard Library contains a class called
exception
in the <exception>
header file (under the std
namespace)
that can serve as a base class
- A Convenient Method:
- The
exception
class contains a virtual member
function what
that returns a null-terminated
char
array that can be overridden/overwritten
to return a description of the exception
There's Always More to Learn