I have just started with exception handling in C++ using try
and catch
blocks. I have a text file with some data and I am reading this file using ifstream
and getline
as shown below,
ifstream file;
file.open("C:\\Test.txt", ios::in);
string line;
string firstLine;
if (getline(file, line, ' '))
{
firstLine = line;
getline(file, line);
}
I would like to know how to implement exception handling in case file.open
fails to open the specified file because it does not exist in the given path, for example there is no Test.txt
in C:
By default iostreams do not throw exceptions. Instead they set some error flags. You can always test if the previous operation succeeded with a contextual conversion to bool:
ifstream file;
file.open("C:\\Test.txt", ios::in);
if (!file) {
// do stuff when the file fails
} else {
string line;
string firstLine;
if (getline(file, line, ' '))
{
firstLine = line;
getline(file, line);
}
}
You can turn on exceptions with the exceptions
member function. I find that more often than not, doing this doesn't help much because you can no longer do things like while(getline(file, line))
: such an loop would only exit with an exception.
ifstream file;
file.exceptions(std::ios::failbit);
// now any operation that sets the failbit error flag on file throws
try {
file.open("C:\\Test.txt", ios::in);
} catch (std::ios_base::failure &fail) {
// opening the file failed! do your stuffs here
}
// disable exceptions again as we use the boolean conversion interface
file.exceptions(std::ios::goodbit);
string line;
string firstLine;
if (getline(file, line, ' '))
{
firstLine = line;
getline(file, line);
}
Most of the time, I don't think enabling exceptions on iostreams is worth the hassle. The API works better with them off.
IOstreams give you the option of turning on exceptions for various state bits. The reference has a very clear example which is exactly what you were asking for.
Well, it all depends what you want to do if the file doesn't exist.
The code as it is at the moment (assuming this is main
) will just exit the process.
However if this is a function call then you probably want to add exception handling around the call to this function.
E.g.
try
{
OpenAndReadFile( std::string filename );
}
catch ( std::ifstream::failure e )
{
// do soemthing else
}
catch ( OtherException e )
{
}
catch ( ... )
{
// All others
}
This assumes that exception throwing is turned on for the ifstream
.