Re: Rethrow from other place than catch-block
* mathiasn:
Is it legal to rethrow an exception from a function called from the
catch block?
Yes, but it's not supported by some older compilers, in particular, it's
not supported by Visual C++ 6.0 and earlier (a compiler bug wrt.
destructor calls).
Is the following program legal C++?
No, because
1) it's lacking
#include <ostream>
;-)
2) it's using a non-standard startup function '_tmain'; of course
that's meant to be defined as a preprocessor symbol 'main' when
building the program, but it won't compile without such def.
#include <iostream>
using namespace std;
void ExceptionHandler(const char* context)
{
cout << "In ExceptionHandler(" << context << "):";
try // Setup a new try-block and rethrow the exception
{
throw;
}
catch (const int& e)
{
cout << "int = " << e << "\n";
}
catch (const char* e)
{
cout << "text = " << e << "\n";
}
catch (...)
{
cout << "UNKNOWN\n";
}
}
int _tmain(int argc, _TCHAR* argv[])
{
for (int i = 0; i < 5; ++i)
{
try
{
switch (i)
{
case 0: throw 42;
case 1: throw "Some text";
case 2: throw 12.4;
case 3: cout << "Still alive\n"; break;
case 4:
{
try
{
throw "Another text";
}
catch (...)
{
ExceptionHandler("Other context");
}
}
break;
}
}
catch (...) // Catch all exceptions here
{
ExceptionHandler("Inside for loop");
}
}
return 0;
}
This small testprogram compiles and runs as expected with Visual C++
2005. But in our bigger system we are expecting that code like this is
causing problems.
I would also expect that, because the function breaks a golden rule of
design: separation of concerns.
Let the function return the information needed to process the exception,
e.g., some descriptive text, or let it rethrow the exception with some
project-standard exception type.
Don't let it process the exception: it doesn't know what's appropriate.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]