ifstream f;
f.open(fileName);
if ( f.fail() )
{
// I need error message here, like "File not found" etc. -
// the reason of the failure
}
How to get error message as string?
Every system call that fails update the errno value.
Thus, you can have more information about what happens when a ifstream open fails by using something like :
cerr << "Error: " << strerror(errno);
However, since every system call updates the global errno value, you may have issues in a multithreaded application, if another system call triggers an error between the execution of the f.open and use of errno.
On system with POSIX standard:
errno is thread-local; setting it in one thread does not affect its
value in any other thread.
Edit (thanks to Arne Mertz and other people in the comments):
e.what() seemed at first to be a more C++-idiomatically correct way of implementing this, however the string returned by this function is implementation-dependant and (at least in G++'s libstdc++) this string has no useful information about the reason behind the error...
You could try letting the stream throw an exception on failure:
std::ifstream f;
//prepare f to throw if failbit gets set
std::ios_base::iostate exceptionMask = f.exceptions() | std::ios::failbit;
f.exceptions(exceptionMask);
try {
f.open(fileName);
}
catch (std::ios_base::failure& e) {
std::cerr << e.what() << '\n';
}
e.what(), however, does not seem to be very helpful:
I tried it on Win7, Embarcadero RAD Studio 2010 where it gives "ios_base::failbit set" whereas strerror(errno) gives "No such file or directory."
On Ubuntu 13.04, gcc 4.7.3 the exception says "basic_ios::clear" (thanks to arne)
If e.what() does not work for you (I don't know what it will tell you about the error, since that's not standardized), try using std::make_error_condition (C++11 only):
catch (std::ios_base::failure& e) {
if ( e.code() == std::make_error_condition(std::io_errc::stream) )
std::cerr << "Stream error!\n";
else
std::cerr << "Unknown failure opening file.\n";
}
Following on #Arne Mertz's answer, as of C++11 std::ios_base::failure inherits from system_error (see http://www.cplusplus.com/reference/ios/ios_base/failure/), which contains both the error code and message that strerror(errno) would return.
std::ifstream f;
// Set exceptions to be thrown on failure
f.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try {
f.open(fileName);
} catch (std::system_error& e) {
std::cerr << e.code().message() << std::endl;
}
This prints No such file or directory. if fileName doesn't exist.
You can also throw a std::system_error as shown in the test code below. This method seems to produce more readable output than f.exception(...).
#include <exception> // <-- requires this
#include <fstream>
#include <iostream>
void process(const std::string& fileName) {
std::ifstream f;
f.open(fileName);
// after open, check f and throw std::system_error with the errno
if (!f)
throw std::system_error(errno, std::system_category(), "failed to open "+fileName);
std::clog << "opened " << fileName << std::endl;
}
int main(int argc, char* argv[]) {
try {
process(argv[1]);
} catch (const std::system_error& e) {
std::clog << e.what() << " (" << e.code() << ")" << std::endl;
}
return 0;
}
Example output (Ubuntu w/clang):
$ ./test /root/.profile
failed to open /root/.profile: Permission denied (system:13)
$ ./test missing.txt
failed to open missing.txt: No such file or directory (system:2)
$ ./test ./test
opened ./test
$ ./test $(printf '%0999x')
failed to open 000...000: File name too long (system:36)
The std::system_error example above is slightly incorrect. std::system_category() will map the error codes from system's native error code facility. For *nix, this is errno. For Win32, it is GetLastError(). ie, on Windows, the above example will print
failed to open C:\path\to\forbidden: The data is invalid
because EACCES is 13 which is the Win32 error code ERROR_INVALID_DATA
To fix it, either use the system's native error code facility, eg on Win32
throw new std::system_error(GetLastError(), std::system_category(), "failed to open"+ filename);
Or use errno and std::generic_category(), eg
throw new std::system_error(errno, std::generic_category(), "failed to open"+ filename);
Related
I am using the following C++ code from the boost library :
try{
child c(commandString, (std_out & std_err) > pipe_stream);
} catch(process_error &pe){
cout<<pe.what()<<" second line"<<endl;
}
The commandString is a command like ls or any other command. But if a command that does not exist is typed as per the documentation it throws the process_error exception.
I am catching the exception here but not sure if there is a better way to print out the details of the exception or error than pe.what() above?
If you look at the boost reference about boost::process::process_error, you can read this:
struct process_error : public system_error {
};
It merely inherits std::system_error but can then be distinguished in the catch-block from other system errors.
emphasis mine
If you look then at the std::system_error reference, like all other standard exceptions, what() is the way to provide detailed information about the raised error so I would say yes, this is the proper way to print out the exception details.
But since boost::process::process_error does not override the what() function, it would return the same as a std::system_error would.
An alternative interface is using std::error_code.
There are pros and cons:
PRO: it enables you to get more detail about where an error condition arose. (This is a hypothetical difference because it's not specified whether what() may include info beyond an error condition)
CON: it might not get as much detail as in the exception message
CON: since some errors are exceptional, it's harder to express the possible error conditions in the interface: the error conditions get in the way in a way that exceptions do not
in your code you might have created this problem by handling exceptions: now how do decide what value(s) to return
NEUTRAL: you may still have to handle exceptions because exceptions can arise from any related code (e.g. during setup, doing allocations).
NEUTRAL: the code() member of boost::process::process_error is likely to be 100% identical to the error_code that you get
Demo
Contrast the implementations and output below:
Live On Coliru
#include <boost/process.hpp>
#include <iostream>
namespace bp = boost::process;
int using_exceptions(std::string const& commandString) {
try {
bp::pstream pipe_stream;
bp::child c(commandString, (bp::std_out & bp::std_err) > pipe_stream);
c.wait();
return c.exit_code();
} catch (std::exception const& e) {
std::cerr << "Exception: " << e.what() << std::endl;
return -1; // WHAT TO RETURN
}
}
int using_error_code(std::string const& commandString) {
try {
bp::pstream pipe_stream;
std::error_code ec;
bp::child c(commandString, (bp::std_out & bp::std_err) > pipe_stream,
ec);
if (ec) {
std::cerr << "Cannot spawn child process: " << ec.message() << "\n";
return -1; // WHAT TO RETURN?
} else {
c.wait(ec);
std::cerr << "Error: " << ec.message() << "\n";
return c.exit_code();
}
} catch (std::exception const& e) {
std::cerr << "Exception: " << e.what() << std::endl;
return -1; // WHAT TO RETURN
}
}
int main()
{
auto cmd = "/usr/bin/bogus";
std::cout << "Using error_code: " << using_error_code(cmd) << "\n";
std::cout << "Using exceptions: " << using_exceptions(cmd) << "\n";
}
Prints
Using error_code: Cannot spawn child process: No such file or directory
-1
Using exceptions: Exception: execve failed: No such file or directory
-1
Is there any significant advantage of using std::cerr instead of std::cout in the below snippest
try{
//codes that can throw go here.
}std::catch(std::exception const& e) {
std::cerr << "Exception " << e.what();
}
.
The "err" in cerr is short for "error". It's intended for error messages. It writes to the error output stream, which, on UNIX-like systems, still writes to the console when you redirect the standard output stream. When you redirect output to a file, you usually don't want error messages intertwingled with the normal output and sent to the file.
I tried the example program from here (with mingw-w64). The program crashed. So I edited it:
#include <iostream> // std::cerr
#include <fstream> // std::ifstream
int main()
{
std::ifstream file;
file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try {
file.open("not_existing.txt");
while (!file.eof())
file.get();
file.close();
}
catch (std::ifstream::failure e) {
std::cerr << "Exception opening/reading/closing file\n";
}
catch (const std::exception& e) {
std::cerr << "should not reach this";
}
return 0;
}
Now it runs, but prints should not reach this, while I was expecting it to print Exception opening/reading/closing file.
Why is my expectation wrong?
EDIT:
since this seems to be an important point, here's the exact version om my compiler: mingw-w64 version "x86_64-6.2.0-posix-sjlj-rt_v5-rev1" , i.e. GCC version 6.2
This may be a MingW bug. I get the expected result using MacOS Clang 802.0.42. The expected output being:
Exception opening/reading/closing file
This might be a known regression: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66145
RapidXml throws an exception in case of an invalid XML file. Is it possible to recover from such a failure?
For example, is it possible to check if the XML is valid beforehand, or recover and continue on?
It seems that when such failures happen, there is only assert and exit of process, and no chance for recovery.
By default, RapidXML raises exceptions on parse errors; it doesn't assert (perhaps by assert you just meant the process aborts).
It is possible to configure RapidXML with your own error handler called rapidxml::parse_error_handler if you #define RAPIDXML_NO_EXCEPTIONS before including the RapidXML headers, and if such an error handler returns, RapidXML will call assert(0), but I suspect that you don't have that enabled and you just need to be catching the right exception.
There's just one exception to catch for parse errors, and it's called rapidxml::parse_error, but RapidXML will also throw std::runtime_error if it fails to find the file.
Here's an example which catches both exception types, plus some catch-all handlers:
#include <iostream>
#include "rapidxml.hpp"
#include "rapidxml_utils.hpp"
int main()
{
try
{
rapidxml::file<> xmlFile("test.xml");
rapidxml::xml_document<> doc;
doc.parse<0>(xmlFile.data());
}
catch (const std::runtime_error& e)
{
std::cerr << "Runtime error was: " << e.what() << std::endl;
}
catch (const rapidxml::parse_error& e)
{
std::cerr << "Parse error was: " << e.what() << std::endl;
}
catch (const std::exception& e)
{
std::cerr << "Error was: " << e.what() << std::endl;
}
catch (...)
{
std::cerr << "An unknown error occurred." << std::endl;
}
}
I open two files, one input and one output. I'd like to handle exceptions for both of them, so by looking at some examples, I made this:
std::ifstream readFile;
readFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
//set the flags for stream bits that indicate failure if ON
std::ofstream writeFile;
writeFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
try{
readFile.open(inputFileName);
writeFile.open(outputFileName);
function(readFile, writeFile);
readFile.close();
writeFile.close();
}
catch(std::ifstream::failure &readErr) {
std::cerr << "\n\nException occured when reading a file\n"
<< readErr.what()
<< std::endl;
return -1;
}
catch(std::ofstream::failure &writeErr) {
std::cerr << "\n\nException occured when writing to a file\n"
<< writeErr.what()
<< std::endl;
return -1;
}
This seems like a reasonable solution, but I get a warning:
warning: exception of type 'std::ios_base::failure' will be caught [enabled by default]
catch(std::ofstream::failure &writeErr) {
^
The code does it's thing, but I'm still interested in improving my code. Where have I wronged?
No you can't. The typedef of std::ifstream::failure and std::ofstream::failure are both defined to be std::ios_base::failure.
The best thing you could do is wrap the individual calls with try-catch:
try
{
readFile.open(inputFileName);
}
catch(std::ifstream::failure &readErr)
{
}
try
{
writeFile.open(outputFileName);
}
catch(std::ofstream::failure &writeErr)
{
}
Or check the state of the streams individually in the catch block to see who failed.
The only way to handle exceptions from the two files separately would be to catch the exception and then check the failbit on the streams to determine which of them that failed:
try
{
readFile.open(inputFileName);
writeFile.open(outputFileName);
function(readFile, writeFile);
readFile.close();
writeFile.close();
}
catch (const std::ios_base::failure &err)
{
if (readFile.fail())
{
std::cerr << "\n\nException occured when reading a file\n"
<< readErr.what()
<< std::endl;
}
if (writeFile.fail())
{
std::cerr << "\n\nException occured when writing to a file\n"
<< writeErr.what()
<< std::endl;
}
return -1;
}