/* signal_cpp.cpp * Stephanie Taylor * There is a difference between exceptions and signals * In particular, if an exception is caught (even all the way at the top * of the call stack), then any object on the stack will have its * destructor called. This does not happen for a signal. */ #include #include #include using namespace std; class hammer { private: int *field_a; public: // constructor hammer() { cout << "constructing a hammer" << endl; field_a = NULL; } // assume that the field has been given a value that isn't // null, and print it out. void print_hammer_val() { printf( "in print_hammer_val\n" ); // If we use an exception, things will go better. //if (field_a == NULL) { //printf( "about to throw\n" ); //throw invalid_argument("don't derefence null pointers!"); //} // If the if-statement above is commented out, then // we will have a signal instead. // The dereference in the printf causes a segmentation fault. cout << *field_a << endl; } // destructor ~hammer() { cout << "destructing a hammer" << endl; } }; void seghandler(int signal) { printf("\nCaught seg fault %d\n", signal); //return; exit(-1); } int main() { signal(SIGSEGV, seghandler); try { hammer h; h.print_hammer_val(); } catch (invalid_argument) { cout << "caught exception" << endl; } }