Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing custom exception in default clause of switch generates single character

Tags:

c++

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.

like image 528
jgrant Avatar asked Jan 15 '23 00:01

jgrant


1 Answers

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.

like image 118
Armen Tsirunyan Avatar answered Jan 31 '23 22:01

Armen Tsirunyan