exception handling

writing a program that requires exception handling. if an error occurs, i what the program to go back to the begging of the loop. i tried using break but that just makes the program crash when it receives a bad input. how do i do this? this is what i have so far (this part of the program any ways)

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
while (! quit)
    {
        // Output phone book menu
        cout << endl
            << "Phone Book Menu\n"
            << "1: add a listing\n"
            << "2: find a listing\n"
            << "3: print phone book\n"
            << "q: quit\n\n"
            << "Choice: ";

        // Input text typed by user
        string choice;
        cin >> ws;            // skip initial whitespace
        getline(cin, choice); // input user text
        Name name;
        PhoneNumber number;
        if (choice == "1")       // Add a listing
        {
            cout << "Add a Listing\n";
            cout << "Enter listing name: ";
            try
            {
            cin >> name;
            }
            catch ( InvalidLength e )
            {
                cerr << e.what() << endl;
                break;
            }
            cout << "Enter listing phone number: ";
            cin >> number;
            phoneBook.add(name, number);
        }

        else if (choice == "2")  // Find a listing
        {
            cout << "Find a Listing\n";
            cout << "Enter name to find: ";
            cin >> name;
            cout << phoneBook.find(name) << endl;
        }

        else if (choice == "3")  // Print phone book
        {
            cout << "Print Phone Book\n";
            cout << phoneBook;
        }

        else if (choice == "q")  // Quit
        {
            cout << "Good-bye" << endl;
            quit = true;
        }

        else                     // Invalid user input
        {
            cerr << "Invalid choice: " << choice << endl;
        }
    }

Last edited on
Put your try..catch block around the loop body, and don't break out of the loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
while (!quit)
{
    try
    {

        //everything else goes here

    }
    catch ( InvalidLength e )
    {
        cerr << e.what() << endl;
    }
}

Hope this helps.
Last edited on
Topic archived. No new replies allowed.