diff --git a/.gitignore b/.gitignore index eb1a3e2..2ac684a 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,4 @@ shared_ptr casts classes lvalues +bad_alloc diff --git a/CMakeLists.txt b/CMakeLists.txt index d03d752..d3e8f8d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -16,3 +16,4 @@ add_executable(shared_ptr shared_ptr.cpp) add_executable(casts casts.cpp) add_executable(classes classes.cpp) add_executable(lvalues lvalues.cpp) +add_executable(bad_alloc bad_alloc.cpp) diff --git a/bad_alloc.cpp b/bad_alloc.cpp new file mode 100644 index 0000000..3e68306 --- /dev/null +++ b/bad_alloc.cpp @@ -0,0 +1,30 @@ +// https://www.cs.uaf.edu/2010/spring/cs202/lecture/03_02_exceptions.html + +#include + +using namespace std; + +void dr_evil(int counter) { + int *array = new int[100000000000/(1+10*counter)]; + cout << "Bwah ha ha!" << endl; + delete[] array; +} + +int foo(void) { + for (int counter=0; counter<10; counter++) { + try { + cout << "About to call dr_evil with counter == " << counter << endl; + dr_evil(counter); + + cout << "I guess he's not so evil!" << endl; + break; + } catch (std::bad_alloc &e) { + cout << "Caught an exception: " << e.what() << endl; + } + } + return 0; +} + +int main(void) { + foo(); +}