执行期间C ++类成员函数错误/异常处理

时间:2017-06-18 00:42:34

标签: c++ exception assert

我有一个使用一个公共方法创建C ++ Tokenizer类的作业 vector * GetTokens(void);

该函数在via stdin中取一个字符串,对字符串进行标记,然后返回size()= 1或2的标记的向量指针。函数需要在以下情况下抛出错误:有0个标记,超过2个令牌,当第一个令牌不是String时,或者第一个令牌不是String而第二个令牌不是Integer时。

Code that calls my function from professor:
//////////////////////
For (int i=0; i <5; i++) {
  Tokenizer tok;
  Vector<string> *test = tok.GetTokens ();

  If (test->size ()==1)  {
    cout << "Yay" << endl;
  } else {
    cout  << "Boo" << endl;
  }
///////////////

我已成功完成此程序以进行正确的标记化。我也是通过if ... then语句打印错误。但是,在我的错误中,cout&lt;&lt; “Yay​​”或“Boo”仍打印出来。我需要在没有允许for循环/调用函数继续执行的情况下打印出这个文本。

有没有办法,在我的GetTokens()方法中使用断言的异常或错误来基本上停止执行,打印我的错误文本,将控制权传递回调用函数而不打印任何其他文本并进入下一个循环周期? :::: EDIT ::::

My Tokenizer.cpp
///////////////////


'//Constructor
Tokenizer::Tokenizer( void ) { }

//This includes my tokenization with my error/exception handling
vector<string> * Tokenizer::GetTokens() {
string strIN;
cout << "> ";
getline(cin, strIN);

vector<string> *tokens = atokenizer(strIN);

//So with one of my constraints, I need to print an error for 0 tokens
try{
    if(tokens->size()!=0) {
        return tokens;
    } else {
        throw tokens;
    }
}
catch(vector<string> *error) {
    cout << "ERROR!" << endl;
    return error;
}
}

//This is my tokenization function which parses by whitespace
vector<string> *Tokenizer::atokenizer(string strIN) {
vector<string> *tokens = new vector<string>();

string token="";
int c=0;
bool whiteSpace=true;

//Iterates thru all chars and tokenizes by " "
for(int i=0; i<strIN.size(); i++) {
    //Checks if char==1-0,a-z,etc. or is space=" "
    if((strIN[i]>=33) && (strIN[i]<=126)) {
        //If char, appends to token
        token+=strIN[i];
        whiteSpace=false;
    }
    else if((strIN[i]==32) && (whiteSpace==false)) {
        //If space, adds token to tokens
        tokens->push_back(token);
        token="";
        c++;
        whiteSpace=true;
    }
}

//Adds final token
if(token!="") {
    tokens->push_back(token);
}

return tokens;
}'
//////////////////

1 个答案:

答案 0 :(得分:0)

所以我想出了一个不同的方法来解决我的问题。我无法使用任何错误处理或异常。相反,我只是回到使用If ... then ... else语句用cout进行错误检查,然后我创建了控制打印输出的函数。

import time
for _ in range(20):
    print('Error!', end=' ', flush=True) # flush courtesy inspectorG4dget to disable buffering
    time.sleep(0.2)