Hello. I've been working recently on a recursive expression parser and have gotten to the phase of handling exceptions, such as division by zero, using non-numerical non-operator characters, and other syntax errors. I've read a few tutorials and references on exception handling, but I'm still a bit lost. I have code that works fine to handle errors, but just because it works doesn't mean it's right. I'm pretty certain that I have (1) unnecessary statements and (2) missing statements that would allow my program to run more efficiently.
Essentially, my question is in regards to the proper syntax and conventions when it comes to handling exceptions in C++.
Here is a snippet of the .cpp which contains a class, constructor (I think), and function to handle a few syntax errors:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
class syntaxErr{
public:
syntaxErr();
};
syntaxErr::syntaxErr(){}
void syntax(const string & s){
//Array of operators which cannot be next to one another
const char ops[] = "*/";
//Parentheses counter
int parenth = 0;
char ind, rInd;
if(s.at(s.length() - 1) == ')' || s.at(s.length() - 1) == '(')
parenth++;
for(unsigned int i = 0; i < s.length() - 1; i++){
ind = s.at(i);
rInd = s.at(i + 1);
if((ind == ops[0] || ind == ops[1]) && (rInd == ops[0] || rInd == ops[1]))
//If the two aformentioned operators are next to one another
//without a number between them, throw a syntax error.
throw syntaxErr();
else if(ind == '(' || ind == ')')
parenth++;
}
if(parenth % 2 != 0)
//If open and closed parentheses are not equal in number
//throw a syntax error
throw syntaxErr();
}
|
Again, it works fine, but it doesn't seem correct.
And here is a snippet of code from a separate .cpp which is used to catch exceptions:
1 2 3 4 5 6 7 8
|
try{
syntax(s);
}
catch(syntaxErr){
cerr << "Error: syntax error" << endl;
cin.get();
exit(1);
}
|
Any help/tips would be greatly appreciated.