Throwing a custom exception in the default ad for the switch generates a single character

I have a custom exception that I use to catch various errors in the whole school project I'm working on.

class WrongValueException : public std::runtime_error { public: WrongValueException(std::string mess): std::runtime_error(mess) {}; }; 

The problem is that I used a "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 passed to the swtich statment should be one of the operators listed in the swtich statement, if that is not what I want to throw an exception. When an exception is thrown, I get only one character, which changes based on the character specified in the input.

I will catch the error in the main function.

Input and output examples:

 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 β€œPress any key to continue ...” is what changes when the operator changes. I successfully completed this error, catching several other checks that I have in my program and throwing a bubble to the main try / catch clause without any problems. This is the only one.

+4
source share
2 answers

You should not use + with string literals. It behaves differently than you think. You must first overlay the string

 throw WrongValueException(std::string("Error: Syntax - ") + operation); 

Otherwise, you pass the address of the character with an offset equal to the numerical value of operation . "Hello"+1 is a pointer to 'e' . In your case, you break out of the binding, and you essentially have undefined behavior.

+6
source

In "Error: Syntax - " + operation you add char to const char * . This performs the addition of a pointer instead of concatenating strings because std::string not involved.

Transfer one of the operands to string :

 std::string("Error: Syntax - ") + operation 
+3
source

All Articles