Thread: Exceptions "try, catch, and throw Statements" ???

  1. #1
    Registered Abuser Loic's Avatar
    Join Date
    Mar 2007
    Location
    Sydney
    Posts
    115

    Exceptions "try, catch, and throw Statements" ???

    Hi all, I wanted to create a program that will tell me how items I can push onto a string vector before the computer runs out of memory and crashes. Now I remember at uni we touched on Exceptions. And I think that that is what I need to be using. But I cant remember how to use them… below I have what I have tried to do so far, but it doesn’t seem to work.


    Code:
    vector<string> wordlist;
    unsigned long long int count = 0;
    try{
        for(;;){
            wordlist.push_back("wordblahhello");
            count++;
            throw count;
        }
    }
    catch(unsigned long long int count){
        cout << count << endl;
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    I suspect that it should be something like this:
    Code:
    vector<string> wordlist;
    unsigned long int count = 0;
    try {
        for (;;) {
            wordlist.push_back("wordblahhello");
            ++count;
        }
    }
    catch (const std::bad_alloc& e) {
        cout << count << endl;
    }
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered Abuser Loic's Avatar
    Join Date
    Mar 2007
    Location
    Sydney
    Posts
    115
    Thanks laserlight, that worked perfectly

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Long-lasting objects that throw exceptions
    By drrngrvy in forum C++ Programming
    Replies: 7
    Last Post: 10-05-2006, 04:30 PM
  2. Unhandled exceptions (throw with no try)
    By Mario F. in forum C++ Programming
    Replies: 3
    Last Post: 07-01-2006, 06:31 AM
  3. Try...catch...throw or ifs?
    By Kylecito in forum C++ Programming
    Replies: 9
    Last Post: 03-02-2006, 10:41 PM
  4. causing default exceptions to throw additional info
    By lightatdawn in forum C++ Programming
    Replies: 14
    Last Post: 08-06-2003, 06:39 PM
  5. Why throw exceptions?
    By Brown Drake in forum C++ Programming
    Replies: 2
    Last Post: 11-02-2001, 06:24 PM