// Test driver for exception handling of MyString class #include "MyString.h" #include int main() { // Set heap limit to 100K bytes to trigger memory alloc failures struct rlimit rl; rl.rlim_cur = rl.rlim_max = 100000; setrlimit(RLIMIT_DATA, &rl); // Loop to keep going after exceptions. Test counter advances // so we cycle through all the test cases. int test = 1; bool done = false; while (!done) try { MyString s1 = "Hello, world"; MyString s2 = "This is a slightly longer string, but not too long."; switch (test) { case 1: // Sanity test of a string cout << "s1 is:" << s1 << ", and s1.length() is " << s1.length() << endl; ++test; case 2: // Another sanity test of a string cout << "s2 is:" << s2 << ", and s2.length() is " << s2.length() << endl; ++test; case 3: // Use of negative character index cout << "s1[-5] is " << s1[-5] << endl; ++test; case 4: // Use of valid character index cout << "s1[3] is " << s1[3] << endl; ++test; case 5: // Is this the last character in the string? cout << "s1[s1.length()] is " << s1[s1.length()] << endl; ++test; case 6: // Use of excessive character index cout << "s1[s1.length() + 5] is " << s1[s1.length() + 5] << endl; ++test; case 7: // Valid substring test cout << "s1(2, s1.length()/2) is " << s1(2, s1.length()/2) << endl; ++test; case 8: // Invalid substring test cout << "s1(s1.length()-2, s1.length()/2) is " << s1(s1.length()-2, s1.length()/2) << endl; ++test; case 9: // String allocation that runs out of memory for (int i = 0; i < 1000; ++i) { // Append s2 to itself so its length keeps doubling s2 = s2 + s2; cout << "s2.length() is " << s2.length() << endl; } ++test; default: done = true; } } catch (const MyString::Error & err) { // Report the caught exception, then continue to the next test cout << endl << " ***** Caught string error: " << err << endl; ++test; } return 0; }