抛出 an exception
抛出错误,使用try throw catch
捕捉
定义一个Exception类
1 2 3 4 5 6 7 8 9 10 11
| class BadLengthException{// 这是一个exception类 public: int length; BadLengthException(int n){ this->length = n; //参数初始化 } int what() const;//创建一个what方法,后面加const表明该函数权限是只读,无法改变成员变量的值 }; int BadLengthException::what() const{ return length; }
|
使用try->throw->catch
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| bool checkUsername(string username) { bool isValid = true; int n = username.length(); if(n < 5) { throw BadLengthException(n);//抛出异常 } for(int i = 0; i < n-1; i++) { if(username[i] == 'w' && username[i+1] == 'w') { isValid = false; } } return isValid; }
try { bool isValid = checkUsername(username); if(isValid) { cout << "Valid" << '\n'; } else { cout << "Invalid" << '\n'; } } catch (BadLengthException e) { cout << "Too short: " << e.what() << '\n'; }
|