- Forward


Exceptions in C++
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • The Problem:
    • Your method can't handle the values its been given
  • One Example:
    • A calculation that results in a negative price
  • One Solution:
    • Return a "special value"
Questions and Observations
Back SMYC Forward
  • 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
Back SMYC Forward
  • 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.)
Back SMYC Forward
  • Syntax:
    • try {statement} catch(exception name) {[statement;]...}
  • An Example:
    • try { d = StringToDouble(s); } catch (NumberFormatException &nfe) { cerr << s << " can not be converted!" << endl; }
The try-catch Statement (cont.)
Back SMYC Forward

Writing an Exception Class - The Specification

cppexamples/exceptions/NumberFormatException.h
 
The try-catch Statement (cont.)
Back SMYC Forward

Writing an Exception Class - The Implementation

cppexamples/exceptions/NumberFormatException.cpp
 
The try-catch Statement (cont.)
Back SMYC Forward

Using an Exception Class in Another Class - The Specification

cppexamples/exceptions/StringConverter.h
 
The try-catch Statement (cont.)
Back SMYC Forward

Using an Exception Class in Another Class - The Implementation

cppexamples/exceptions/StringConverter.cpp
 
The try-catch Statement (cont.)
Back SMYC Forward

Using an Exception Class- Use

cppexamples/exceptions/Driver.cpp
 
Overuse
Back SMYC Forward
  • 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
Back SMYC Forward
  • 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
Back -