遇到异常时给定函数的返回值是多少
What is the return value of the given function on encountering an exception?
>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
不关心该函数中发生了什么,只打印"太短:"
相关文章:
- 从python中调用C++函数并获取返回值
- 为什么模板类中的对象不能返回值
- 返回值优化:显式移动还是隐式
- lock_guard是否保护返回值
- 调用CreateProcess()并获取字符串的返回值
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 查找 GCD:并非所有控制路径都返回值
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 如何从 std::thread 返回值
- 将返回值从 exe 传递到 bat,并将其传递给 C# 中的进程
- 方法错误"not all control paths return a value"和方法不返回值
- 如何读取 C++ SAFEARRAY**,该 SAFEARRAY** 是 COM 互操作的结果,其中 C# 返回值为
- 对fread的返回值感到困惑
- 在没有返回值优化的情况下将两个对象加在一起时,将创建多少个临时对象
- 遇到异常时给定函数的返回值是多少
- "stringstream>>something"的返回值是多少?
- 缺少返回语句的非 void 函数的返回值是多少?
- 当size为0时,STRNCMP的返回值是多少?