3.2 Throw exceptions
Listing 2 is the second implementation of readnums. It includes the basic logic in listing 1. However, this newer version also
includes exception throwing code.
1class Exception
2{ 3 char message[256];
4 public:
5 Exception(
const char *m)
{ strncpy(message, m,
sizeof(message));
} 6 virtual const char *getMessage(
void)
{ return message;
} 7};
8 9class BadPath :
public Exception
10{ 11 public:
12 BadPath(
const char *m):Exception(m)
{} 13};
14 15class BadInt :
public Exception
16{ 17 public:
18 BadInt(
const char *m):Exception(m)
{} 19};
20 21class TooBig :
public Exception
22{ 23 public:
24 TooBig(
const char *m):Exception(m)
{} 25};
26 27unsigned readnums(
const char *path,
int array[],
unsigned n)
28 throw (BadPath, BadInt, TooBig)
29{ 30 // read up to n integers from the file at path 31 ifstream file;
32 unsigned i;
33 34 file.open(path);
35 if (!file.is_open())
36 { 37 throw BadPath(”bad_path,_file_cannot_be_opened_for_reading”);
38 } 39 i = 0;
40 while (!file.eof() && (i
< n))
41 { 42 file
>> array[i];
43 if (file.fail())
44 { 45 file.close();
46 throw BadInt(”bad_integer_format”);
47 } 48 } 49 file.close();
50 if (!file.eof() && (i == n))
51 { 52 throw TooBig(”too_many_integers_in_the_file”);
53 } 54 return i;
55}
Line 28 is a part of the function prototype that indicates this function can throw exceptions.
The conditional statement on line 35 checks to see if the file is open. If not, it throws a BadPath exception. Note that
BadPath is a subclass of Exception. The keyword throw will be explained later. For the time being, we will simply see throw
as a very special return.
The conditional statement on line 43 checks to see if an integer is read. If there is a format error, the conditional
statement closes the file first, then throws a BadInt exception.
The conditional statement on line 50 checks to see if there is anything else in the file. If so, it throws a TooBig
exception.