Results 1 to 2 of 2

Thread: Catch the exception

  1. #1

    Thread Starter
    Addicted Member Ramandeep's Avatar
    Join Date
    Feb 2000
    Posts
    158

    Question Catch the exception

    How can I catch a exception were I'm expecting an integer but the user enters a real or string.

    Can someone give me a list of the basic exceptions that can be caught?

    I know the format of catching them is as follows, but what do you put in the parenthesis of the catch bit, in Java you code something like catch(NumberFormatException exp) to catch number entry errors etc.

    Code:
    try
    {
        // statements
    }
    
    catch()
    {
        // statements
    }
    Bellow is a small test piece of the project I'm doing and I wish to catch an exception when the users entry is taken at the 'cin' bit.

    Code:
    int menu()
    {
    	int selectedOption = 0;
    
    	do
    	{
                                    clearScreen();
                                    
    		cout << "MAIN MENU" << endl;
    
    		cout << "<1>  Option A" << endl;
    		cout << "<2>  Option B" << endl;
    		cout << "<3>  Option C" << endl;
    		cout << "<4>  Option D" << endl;
    		cout << "<5>  Option E" << endl;
    
    		cout << "\nEnter selection: ";
    
    		cin >> selectedOption;
    	}
    	while((selectedOption < 1) || (selectedOption > 5));
    
    	return selectedOption;
    }

  2. #2
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    You can catch anything that's thrown. You can throw an intrinsic type (such as int, bool, char*, whatever) or an object (it's best to derive from the std::exception class for solidarity).

    For example:
    Code:
    try {
        throw 5;
        throw "Hello";
        throw std::logic_error("Arrrrghh");
        throw std::runtime_error("Whatsit");
    } catch(int i) {
        cerr << i << endl;
    } catch(const char* str) {
        cerr << str << endl;
    } catch(std::exception &ex) {
        cerr << ex.what() << endl;
    }
    Comment out the throw statements you don't want.

    A quick note - virtual inheritance is taken into account of when passing objects, so you should always pass a reference. In this case, the std::exception will catch both the logic_error and the runtime_error. The what() function is guaranteed in subclasses of exception, and makes a much easier way of telling the user what went wrong.
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width