add an example throwing bad_alloc

master
neingeist 11 years ago
parent b987b2badd
commit ddec3de9b6

1
.gitignore vendored

@ -16,3 +16,4 @@ shared_ptr
casts
classes
lvalues
bad_alloc

@ -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)

@ -0,0 +1,30 @@
// https://www.cs.uaf.edu/2010/spring/cs202/lecture/03_02_exceptions.html
#include <iostream>
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();
}
Loading…
Cancel
Save