I have a custom exception built that I am using to catch different errors throughout a school project I am working on.
class WrongValueException : public std::runtime_error
{
public:
WrongValueException(std::string mess): std::runtime_error(mess) {};
};
The problem is when I used "throw WrongValueException("Error: Syntax"); in the default clause of the switch statement below.
Expression* SubExpression::parse()
{
Expression* left;
Expression* right;
char operation, paren;
left = Operand::parse();
cin >> operation;
right = Operand::parse();
cin >> paren;
switch (operation)
{
case '+':
return new Plus(left, right);
case '-':
return new Minus(left, right);
case '*':
return new Times(left, right);
case '/':
return new Divide(left, right);
default:
throw WrongValueException("Error: Syntax - " + operation);
}
return 0;
}
Basically the character that is being passed to the the swtich statment should be one of the operators listed in the swtich statement, if it isn't I want to throw the exception. When the exception is thrown all I get is a single character that changes based on the character given in the input.
I catch the error in the main function.
Examples of input and out are:
Enter expression: (5^x),x=2;
#
Press any key to continue . . .
Enter expression: (5&x),x=2;
T
Press any key to continue . . .
The single characters above the "Press any key to continue..." is what changes when the operator changes. I have successfully implemented this error catching for a few other checks I have in my program and the throws bubble up to the main try/catch clause without issue. This is the only one.
You shouldn't use + with string literals. It behaves differently from what you think. You should cast to a string first
throw WrongValueException(std::string("Error: Syntax - ") + operation);
Otherwise you're passing the address of the character with offset equal to the numeric value of operation
. "Hello"+1
is a pointer to 'e'
. In your case, you go out of bound and you're essentially having undefined behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With