tags:

views:

1236

answers:

3

I'm using fstream is there any way to get the failure message/ excpetion. for example if unable to open the file I want to get the reason for it.

+4  A: 

Streams by default do not throw exceptions on error, they set flags. You can make them throw exceptions by using the stream's exception() member function:

ifstream ifs;
ifs.exceptions( std::ios::failbit );   // throw if failbit get set

Theoretically, you could then do something like this:

try {
  int x;
  ifs >> x;
}
catch( const std::exception & ex ) {
   std::cerr << "Could not convert to int - reason is " 
                  << ex.what();
}

Unfortunately, the C++ Standard does not specify that thrown exceptions contain any error message, so you are in implementation specific territory here.

anon
+1  A: 
Doug
+1  A: 

from checking it out I found that also errno and also GetLastError() do set the last error and checking them is quite helpful. for getting the string message use: strerrno(errno);

sofr