I’m starting to use exceptions and to handle more precisely some events or errors, I created my own type of exceptions derived from std::exception. So far everything went well but I’ve just noticed that sometimes the method what() does not print anything. The exception is well thrown and caught, but the explanation message print normally by the method what() does not always show on screen. It can happen with the same parameters as the previous execution which ended printing the message and seems to be completely random.
Here’s my exceptions :
class MyException : public std::exception
{
public:
MyException() throw() {}
~MyException() throw() {}
virtual const char *what() const throw()
{
return "general exception\n";
}
};
class FileError : public MyException
{
public:
FileError(std::string nFileName) : MyException(), fileName(nFileName) { }
~FileError() throw (){ }
virtual const char *what()
{
std::ostringstream oss;
oss << "Error with file : \"" << fileName << "\"." << std::endl;
return (oss.str()).c_str();
}
protected:
std::string fileName;
};
and the context which cause me problem :
try
{
QFile sourceFile(sourceFileName);
if(!sourceFile.open(QIODevice::ReadOnly))
throw FileError(sourceFileName.toStdString());
sourceFile.close();
}
catch(FileError &e)
{
std::cout << "error file catch " << std::endl;
std::cout << e.what();
terminate();
}
“error file catch” is always print but “Error with file…” sometimes. Any idea what I’m doing wrong ? Thanks
You are returning a pointer to the contents of a temporary std::string.