Re: Error Managment
"JackC" <jecheney@gmail.com> wrote in message
news:1186101699.436015.176220@e9g2000prf.googlegroups.com...
Hi,
If I have a long boolean function that has regular error checking
throughout, and simply returns false upon an error, whats the best
approach to getting detailed information about the error in the code
segment that called the function?
For example in a function:
{
...
open filea
check(filea open failed)
return false
open fileb
check(fileb open failed)
return false
...
}
How could i alter this so that the code that calls the above function
can tell if filea or fileb failed with a detailed error message for
the user?
My theoretical approach, which might be wrong is as follows:
I would create a public variable in my class : string LAST_ERROR;
then set this with detailed information right before 'return false',
then the calling segment could read the contents of last error, and
echo it to the user.
Is this the best approach to error handling? I have heard about using
error codes, but i cant think how i this could be implemented, or if
there is a more standardized method.
As Elas showed, you should throw an exception, although you should inherit
from std::exception. See FAQ 17.6
http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.6
The output of the following program is:
Path1 bad
#include <stdexcept>
#include <fstream>
#include <iostream>
class MyException : public std::runtime_error
{
public:
MyException(const std::string& What ): std::runtime_error(What) { }
};
bool myFun( const char* path1, const char* path2 )
{
std::ifstream fileA( path1 );
if ( !fileA.good() )
throw( MyException("Path1 bad") );
std::ifstream fileB(path2);
if ( !fileB.good() )
throw( MyException("Path2 bad") );
return true;
}
int main()
{
try
{
myFun( "Foo.txt", "Bar.txt" );
}
catch ( std::exception& e )
{
std::cout << e.what();
}
}
I took the exception and modified it from the FAQ. I'm not sure, but you may
be ablet o simply throw std::exception( What ); I don't know, didnt' test
it. Excercise for the reader.