try-catch ?

In a college library, a staff can use the self-service book borrowing system to borrow books without going through librarians. To begin using the system, the staff member is required to enter his/her staff number ( a 4-digit integer value ) into the system. If a non-integer value is entered, the system will catch the exception and display the message “Invalid number”.

Write a try-catch statement that prompts the user for the staff number and displays a message “Welcome”.

How should I do to achieve the goal?
It is worst place ever to use exceptions (if you do not count breaking from loop use).

I think it should be something like:
1
2
3
4
5
6
7
8
9
do {
    int ID(0);
    try {
        ID = getID(); //can throw
    } catch (const InvalidInput& e) {
        std::cout << "Wrong input" <<std::endl;
    }
} while (ID == 0);
std::cout << "Welcome";
Don't use exceptions as you would use return codes.
1
2
3
4
5
6
7
8
try{
   int ID = getID();
   std::cout << "Welcome\n";
   //...
}
catch(const InvalidInput& e){
   std::cerr << e.what() << '\n';
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int main()
{
    std::cin.exceptions( std::ios_base::failbit ) ;

    try
    {
        int n ; std::cout << "number? " && std::cin >> n ;
        std::cout << "welcome\n" ;
    }

    catch( const std::ios_base::failure& e ) { std::cerr << "invalid number\n" ; }
}
Topic archived. No new replies allowed.