On (28 Sep 97) Paul Wankadia wrote to Kevin Krumwiede...
KK> If a function has an exception list specified, and it throws an
KK> exception not on the list, unexpected() will be called. But if the
PW> I've always wanted to know how to do exceptions in C++ ... please
PW> explain.
Exceptions in C++ are conceptually a bit similar to the ON ERROR
conditions in BASIC, though the BASIC version is basically global in
nature while C++'s version is basically block structured (no big
surprise there...)
For example, assume we have a program that uses a configuration file
which MUST exist for the program to operate. In the program, we want to
open that file for use and we'll throw an exception if it doesn't exist:
class bad_file {};
class config_file {
fstream file;
public:
open(char const *filename) throw(bad_file) {
file.open(filename, ios::in | ios::out | ios::binary);
if ( file.bad())
throw(bad_file);
}
};
Now, there are basically two things throwing an exception can do: if the
exception is caught at some point, the code that catches it can try to
fix things up so the code can still work. Alternatively, if nothing
catches the exception, the program will be aborted.
In this example, we'll assume that if the configuration file doesn't
exist, the user hasn't simply hasn't installed the program yet. When
that happens, we simply run a setup program to create a config file,
then we go on from there:
config_file setup;
try {
setup.open("setup.dat");
}
catch(no_temp_file) {
do_setup(setup);
}
This allows us to deal with the error a the spot best able to actually
deal with it correctly, and improves reusability.
For example, the config_file class might be part of a library that
really has no idea what sort of configuration we're dealing with, or how
to create a configuration file that's suitable for your particular
program. As such, it can't include the do_setup() function itself.
I should add that this probably isn't a particularly good example of
exception handling: in this particular case, it would probably be better
for config_file to include a pure virtual function do_setup() that will
get called automatically if the configuration file doesn't exist.
Throwing the exception would then be reserved for the more truly
exceptional conditions such as there not being enough space on the disk
to create the file when it doesn't exist.
However, exceptions appear to be their most useful in extremely large
projects, particularly those that use a number of large components such
as class libraries. Unfortunately, posting the source to a large
project is a LONG ways from practical in the echo.
Later,
Jerry.
--- PPoint 2.02
---------------
* Origin: Point Pointedly Pointless (1:128/166.5)
|