Throwing a filename Exception
Apr 21, 2011 at 11:25pm UTC
How do I, using try, throw, catch, check to see if a file exists. Then if it doesn't it catches the exception and let's the user know. Here's what I have so far
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
string filename;
ifstream infile;
bool loop = false , rand = true ;
while (!loop)
{
rand = true ;
cout << "Please input the file name" << endl;
cin >> filename;
filename = "c://" + filename;
try
{
infile.open(filename.c_str());
}
catch (...)
{
cout << "File not found" << endl;
rand = false ;
}
if (rand)
loop = true ;
}
I also have an exception class simply called Exception, so here's this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#ifndef H_EXCEPTION
#define H_EXCEPTION
#include <stdexcept>
#include <string>
using namespace std;
class Exception : public runtime_error
{
public :
Exception():
runtime_error("The file name is incorrect!" )
{ }
};
#endif
Apr 21, 2011 at 11:51pm UTC
Got it working, nevermind
Topic archived. No new replies allowed.