Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Exception Handling

  • 21-03-2005 08:06PM
    #1
    Closed Accounts Posts: 6


    Hi all,

    I am writing a c++ program that involves exception handling.I am reading in a int value from the user.How can i make sure that they are not inputting a character value.

    I have tried checking this value with the isdigit predefined function ctype.h library.IE if the value is not a digit i throw an exception

    Code:
    if(!isdigit(y))
    {
    throw " Sorry you have entered a character.This is not allowed!!";
    }

    catch (char *str)
    {
    cout << endl<< "Exception: " << str << endl<<endl;
    cout<<"Please try again the Program again!"<<endl;
    exit(0);
    }

    where y is the integer value entered by the user.

    Any help with this would be greatly appreciated,
    Thanks,
    Captain P


Comments

  • Registered Users, Registered Users 2 Posts: 4,003 ✭✭✭rsynnott


    the exception will only be caught if it's thrown within a try block.

    So something like this:

    try{
    doDangerousThing(); // Throws an exception
    doSomethingElse();
    }catch(char *str)
    {
    cout << endl<< "Exception: " << str << endl<<endl;
    cout<<"Please try again the Program again!"<<endl;
    exit(0);
    }

    If it's anything complicated, you might want to consider creating your own Exception objects, so you can quickly see what's going wrong and handle it accordingly.


Advertisement