Classes with exception problem

I have a program that uses class functions to enter and print out info. The problem is with the second function answers(). Here is the whole cpp file. In the answer function I need to use an exception to exit when its the end of an array. I could just be doing it wrong. I used try/catch originally but when I used it, it caught the exception but ended the whole program. Anyone know what I should do?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <cstdlib>
#include "answering_machine.h"
using namespace std;

void AnsweringMachine::init(){
    numMessages = 0;
}

void AnsweringMachine::answer (string messages[MAX_NUM]){
    cout << "Enter words into the string array: " << endl;
    cout << "Type exit when you are done " << endl;
    for (int i=0; i < MAX_NUM; i++){
        cin >> messages[i];
        numMessages++;
        if (messages[i] == "exit")
            throw "No more room";
        }

}

void AnsweringMachine::playback(){
    for (int i=0; i < MAX_NUM; i++)
        cout << messages[i];
}

int AnsweringMachine::getNumMessages(){
    return numMessages;
}

bool AnsweringMachine::haveMessage(){
    if (messages){
        return true;
    }
}

void AnsweringMachine::reset(){
    messages[MAX_NUM].clear();
}
I need to use an exception to exit when its the end of an array.
Why would you do such abomination?

USe break; to stop loop. Use return; to stop function. You can even use goto to break from several nested loops. But exceptions to do something routine? This is perversion.
Throw an exception if there is no room left in the array (i.e., the machine is full)


his words not mine. I agree with you 100% though. If it's not possible then I'll just do as you said.
So you should throw an exception if loop will went up to MAX_NUM, not when user prints exit.
I did that originally but then it won't print out my exception and it won't print out what I typed in.
1
2
3
4
5
6
7
8
    for (int i=0; i < MAX_NUM; i++){
        cin >> messages[i];
        numMessages++;
        if (messages[i] == "exit")
            return;
    }
    if(numMessages >= MAX_NUM)
        trow std::runtime_error("No more room");
You need to include <exception>
Last edited on
whew! thanks I read a little about runtime_error to understand it better (very useful code) so i used it and it worked. Then I fixed my printing function (I was supposed to take a parameter) but now everything is working fine. Thanks!
Topic archived. No new replies allowed.