Re: Catching exceptions
* magnus.moraberg@gmail.com:
I have the following incomplete code -
File file;
file.open(filePath);
try
{
someOneElsesApi::startComplexProcessingOfFile(file);
std::cout << "The file is now processed" << std::endl;
}
catch exception(/* all exceptions */)
{
std::cout << "The file didn't process because: " << std::endl;
}
startComplexProcessingOfFile() can throw a whole range of different
exceptions.
How do I catch them and inform the user in a useful manner. In python,
there is a base exception class which can be used for this purpose. C#
has inner exceptions which I also found quite useful.
If the exceptions are all derived from some base class T (e.g. std::exception),
just do
try
{
// Whatever.
}
catch( std::exception const& x )
{
std::cerr << "!" << x.what() << std::endl;
}
If the exceptions are of unrelated types then you can do
try
{
// Whatever.
}
catch( ... )
{
std::cerr << "!" << exceptionText() << std::endl;
}
where exceptionText is a routine that you have defined tailored to the exception
types you expect, e.g. like
std::string exceptionText()
{
try
{
throw;
}
catch( A const& a )
{
return exceptionTextFrom( a );
}
catch( B const& b )
{
return exceptionTextFrom( b )
}
catch( C const& c )
{
return exceptionTextFrom( c );
}
catch( std::exception const& x )
{
return x.what();
}
catch( ... )
{
return "Uknown exception";
}
}
where exceptionTextFrom might be a routine that you define, or just direct code
to access the exception object's message.
For anything but the smallest program it is however generally a bad idea to
present the message carried by an exception to the user as a main message. It's
probably not adapted to the context it appears in. It's probably about internal
technical details that the user doesn't care about and doesn't have access to.
It's probably expressed in a technical terminology/jargon that the user doesn't
understand. It may even be in a national language that user doesn't understand.
Exception information is generally for programmers (e.g. log it).
Cheers & hth,
- Alf
--
Due to hosting requirements I need visits to <url: http://alfps.izfree.com/>.
No ads, and there is some C++ stuff! :-) Just going there is good. Linking
to it is even better! Thanks in advance!