遇到异常时给定函数的返回值是多少

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

本文关键字:返回值 多少 函数 异常 遇到      更新时间:2023-10-16

>checkUsername()检查用户名的长度,并在长度大于或等于 5 时返回true。否则,它将返回false 。该函数checkUsername()应该在BadLengthException()上返回 false,但它似乎没有出现,因为checkUsername()内没有任何代码,BadLengthException::what()返回false。但是当遇到长度小于 5 的用户名时,程序仍然可以正常工作。这是怎么回事?返回值是如何传递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;
}

函数可以返回值或抛出异常,它不能同时执行这两项操作,它们是互斥的。如果它成功返回一个值,则意味着代码没有引发异常,如果抛出异常,则意味着它没有达到返回值的程度。

此外,捕获返回值也会中断,代码会直接跳转到您定义的catch块。这就像一个概念上的硬goto,如果你忽略自动对象销毁和finally类型实现之类的事情,这些事情将在异常冒泡的过程中发生。

checkUsername()抛出异常时,它会停止该函数中的处理并返回到main()的调用函数。 由于调用是在try块中进行的,因此异常由catch块处理。

if()语句被完全忽略,catch不关心该函数中发生了什么,只打印"太短:"