Re: Error Managment
On 2 ago, 21:41, JackC <jeche...@gmail.com> wrote:
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.
Thanks for any advice,
Jack
Throw an exception. In the following example. If you have a file named
test in the directory you run the executable obtained by compiling the
program below you get:
Path 2 invalid!
The code:
#include <fstream>
#include <iostream>
class ExceptionA {};
class ExceptionB {};
bool myFun( const char* path1, const char* path2 )
{
std::ifstream fileA( path1 );
if ( !fileA.good() ) throw( ExceptionA() );
std::ifstream fileB(path2);
if ( !fileB.good() ) throw( ExceptionB() );
}
int main( int argc, char* argv[], char* env[] )
{
try
{
myFun( "test", "wrong path" );
}
catch ( const ExceptionA& e )
{
std::cerr << "Path 1 invalid!\n";
}
catch ( const ExceptionB& e )
{
std::cerr << "Path 2 invalid!\n";
}
return( 0 );
}
Notice that you do not actually have to create a class for every
possible exception, but, instead, you may include lots of information
in the thrown object with an appropriate constructor. You can then use
it via the "e" reference caught by the catch clause. There is much
more to that, a good source (not only in this subject) is:
http://www.parashift.com/c++-faq-lite/exceptions.html
Elias Salom=E3o Helou Neto.