Datasheet

An exception is an unexpected situation. For example, if you are writing a function that retrieves a Web
page, several things could go wrong. The Internet host that contains the page might be down, the page
might come back blank, or the connection could be lost. In many programming languages, you would
handle this situation by returning a special value from the function, such as the
NULL pointer. Exceptions
provide a much better mechanism for dealing with problems.
Exceptions come with some new terminology. When a piece of code detects an exceptional situation, it
throws an exception. Another piece of code catches the exception and takes appropriate action. The fol-
lowing example shows a function,
divideNumbers(), that throws an exception if the caller passes in a
denominator of zero.
#include <stdexcept>
double divideNumbers(double inNumerator, double inDenominator)
{
if (inDenominator == 0) {
throw std::exception();
}
return (inNumerator / inDenominator);
}
When the throw line is executed, the function will immediately end without returning a value. If the
caller surrounds the function call with a
try-catch block, as shown in the following code, it will receive
the exception and be able to handle it.
#include <iostream>
#include <stdexcept>
int main(int argc, char** argv)
{
try {
std::cout << divideNumbers(2.5, 0.5) << std::endl;
std::cout << divideNumbers(2.3, 0) << std::endl;
} catch (std::exception exception) {
std::cout << “An exception was caught!” << std::endl;
}
}
The first call to divideNumbers() executes successfully, and the result is output to the user. The second
call throws an exception. No value is returned, and the only output is the error message that is printed
when the exception is caught. The output for the preceding block of code is:
5
An exception was caught!
Exceptions can get tricky in C++. To use exceptions properly, you need to understand what happens to
the stack variables when an exception is thrown, and you have to be careful to properly catch and han-
dle the necessary exceptions. The preceding example used the built-in
std::exception exception type,
but it is preferable to write your own exception types that are more specific to the error being thrown.
Unlike the Java language, the C++ compiler doesn’t force you to catch every exception that might occur.
24
Chapter 1
04_574841 ch01.qxd 12/15/04 3:39 PM Page 24