Skip to content

Instantly share code, notes, and snippets.

@CrBoy
Created June 14, 2011 10:28
Show Gist options
  • Save CrBoy/1024649 to your computer and use it in GitHub Desktop.
Save CrBoy/1024649 to your computer and use it in GitHub Desktop.
Something test about C++ exception handling
This is a simple test for:
set_new_handler(),
set_unexpected(), and
set_teminate()
all: set_new_hand set_unexpected set_terminate
set_new_hand: set_new_hand.cpp
g++ -g -o set_new_hand set_new_hand.cpp
set_unexpected: set_unexpected.cpp
g++ -g -o set_unexpected set_unexpected.cpp
set_terminate: set_terminate.cpp
g++ -g -o set_terminate set_terminate.cpp
clean:
rm -f set_new_hand set_unexpected set_terminate
/*
* Use gdb to trace the runtime behavior, you will find that
* the operator new performs the new_handler and allocate the memory again.
* If the new_handler does not produce free memories, it will be a infinite loop.
*/
#include <iostream>
#include <cstdlib>
#include <new>
using namespace std;
const int size = 1000000;
double *mem[size];
void my_hand()
{
cout << "my_hand()" << endl;
//abort();
}
int main(int argc, const char *argv[])
{
set_new_handler(my_hand);
for(int i=0;i<size;i++){
mem[i] = new double[1000000000];
}
return 0;
}
/*
* Throwing an exception in a terminate_handler does no use. (Boooooo~~~~~~~~~~)
*/
#include <iostream>
#include <exception>
using namespace std;
void my_hand()
{
cout << "my_hand()" << endl;
throw 13;
}
void f() throw(int)
{
throw 'a';
}
int main(int argc, const char *argv[])
{
set_terminate(my_hand);
f();
return 0;
}
/*
* Throw an exception in an unexpected_handler to "correct" the type of exception to an expected one.
*/
#include <iostream>
#include <exception>
using namespace std;
void my_hand()
{
cout << "my_hand()" << endl;
throw 13;
}
void f() throw(int)
{
throw 'a';
}
int main(int argc, const char *argv[])
{
set_unexpected(my_hand);
try{
f();
}catch(int e){
cout << e << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment