Kaushal Kishore
Kaushal Kishore

Reputation: 130

What is the return value of the given function on encountering an exception?

checkUsername() checks the username's length, and returns true when length is greater than or equal to 5. Otherwise it returns false. The function checkUsername() should return false on BadLengthException(), but it doesn't seem to appear as none of the code within checkUsername() and BadLengthException::what() returns false. But still the program is working fine when it encounters a username of length less than 5. What's going on here? How is the return value passed false?

class BadLengthException: public exception{
    public:
        int n;
        BadLengthException(int x) { n=x; };
        virtual int what() throw() {
            return n;
        }
    };
/*
This function checks the username's length, 
and returns true when length is greater than or equal to 5.
Otherwise it returns false.
*/
bool checkUsername(string username) {
    bool isValid = true;
    int n = username.length();
    if(n < 5) {
        throw BadLengthException(n);    //the problem
    }
    for(int i = 0; i < n-1; i++) {
        if(username[i] == 'w' && username[i+1] == 'w') {
            isValid = false;
        }
    }
    return isValid;
}

int main() {
    int T; cin >> T;
    while(T--) {
        string username;
        cin >> username;
        try {
            bool isValid = checkUsername(username);
            if(isValid) {
                cout << "Valid" << '\n';
            } else {
                cout << "Invalid" << '\n';
            }
        } catch (BadLengthException e) {
            cout << "Too short: " << e.what() << '\n';
        }
    }
    return 0;
}

Upvotes: 0

Views: 117

Answers (2)

tadman
tadman

Reputation: 211590

A function can either return a value or throw an exception, it can't do both, they're mutually exclusive. If it successfully returns a value that means the code didn't throw an exception, and if an exception was thrown then it means it didn't make it to the point of returning a value.

Further to that, capturing the return value is also interrupted, the code jumps right to the catch block you've defined. It's like a hard goto in concept, if you ignore things like automatic object destruction and finally type implementations which will happen in the process of an exception bubbling up.

Upvotes: 1

Alwyn Schoeman
Alwyn Schoeman

Reputation: 466

When the exception is thrown in checkUsername(), it stops processing in that function and returns to the calling function which is main(). Because the call was made in a try block the exception is handled by the catch block.

The if() statement is completely ignored and the catch doesn't care about what happened in that function and just prints "Too short: "

Upvotes: 1

Related Questions