If a program tries to use my file-reading class to access part of a file that does not exist (i.e., is after ios_base::end), what exception should be thrown?
I was going to use std::out_of_range, but now I’m beginning to think std::runtime_error would be more appropriate.
Edit:
The interface works a bit differently than the standard fstream class in that it’s based around for loops rather than while loops. So instead of doing the following:
while (MyFile.peek() != EOF)
{
char Character = MyFile.get();
// Do stuff with Character.
}
The user of the class can do this:
for (std::streampos Pos = 0; Pos < MyFile.GetCharCount(); Pos++)
{
char Character = MyFile.GetChar(Pos);
// Do stuff with Character.
}
If you’re providing an array-like interface (using operator[], rather
than get), then throwing
std::out_of_rangeis a good idea; a betteridea in this case might be to figure out how many bytes you can actually
access, furnish a size() function, and make being in range
a pre-condition. (Of course, to provide random access like this, you’re
going to have to read the entire file into memory anyway. You can’t
seek to arbitrary positions at random in a text file, except under
Unix.)
If you’re providing a file like interface, then setting an error status,
like iostream does, is the preferred solution.
If you’re providing neither, it’s all a question of what you are
providing, and what user expectations for it are, or should be.