S
Steven T. Hatton
I haven't thought about rethrowing an exception in a long time, and tried to
do it the wrong way. Now I'm curious about /why/ it's wrong. My
expectation was that the exception instance would simply be passed up the
call stack as the same object. It would therefore behave polymorphically.
Is the behavior shown below compiler-specific? I'm using gcc 4.0.2.
In terms of what goes on at runtime, why does the `throw e' act as if I
threw a raw std::exception?
#include <stdexcept>
#include <iostream>
void generate(){
throw std::invalid_argument("generate() invalid argument exception");
}
void handle(bool broken) {
try {
generate();
} catch (std::exception& e) {
std::cout<< "handle:"<< e.what() <<std::endl;
if(broken)throw e;
throw;
}
}
void rehandle(bool broken=false) {
try {
handle(broken);
} catch (std::exception& e) {
std::cout<< "rehandle:"<< e.what() <<std::endl;
if(broken)throw e;
throw;
}
}
int main() {
try {
rehandle();
} catch(std::exception& e) {
std::cout<< "main:"<< e.what() <<std::endl;
}
try {
rehandle(true);
} catch(std::exception& e) {
std::cout<< "main:"<< e.what() <<std::endl;
}
}
/*-----------output---------
handle:generate() invalid argument exception
rehandle:generate() invalid argument exception
main:generate() invalid argument exception
handle:generate() invalid argument exception
rehandle:St9exception
main:St9exception
*/
do it the wrong way. Now I'm curious about /why/ it's wrong. My
expectation was that the exception instance would simply be passed up the
call stack as the same object. It would therefore behave polymorphically.
Is the behavior shown below compiler-specific? I'm using gcc 4.0.2.
In terms of what goes on at runtime, why does the `throw e' act as if I
threw a raw std::exception?
#include <stdexcept>
#include <iostream>
void generate(){
throw std::invalid_argument("generate() invalid argument exception");
}
void handle(bool broken) {
try {
generate();
} catch (std::exception& e) {
std::cout<< "handle:"<< e.what() <<std::endl;
if(broken)throw e;
throw;
}
}
void rehandle(bool broken=false) {
try {
handle(broken);
} catch (std::exception& e) {
std::cout<< "rehandle:"<< e.what() <<std::endl;
if(broken)throw e;
throw;
}
}
int main() {
try {
rehandle();
} catch(std::exception& e) {
std::cout<< "main:"<< e.what() <<std::endl;
}
try {
rehandle(true);
} catch(std::exception& e) {
std::cout<< "main:"<< e.what() <<std::endl;
}
}
/*-----------output---------
handle:generate() invalid argument exception
rehandle:generate() invalid argument exception
main:generate() invalid argument exception
handle:generate() invalid argument exception
rehandle:St9exception
main:St9exception
*/