Question

I am trying to create a calculator. Why can't I catch the EOF error? My program crashes when I input more than one special characters. e.g. 2++

How is this problem normally solved?

Thanks in advance!

def calcfieldcheck(input):
    return re.match("^[0-9\.\-\/\*\+\%]+$",input)
    #uitzoeken hoe regex nesten


def calculate(input):

    print "Wat moet ik berekenen?"

    counter=0


    while not calcfieldcheck(input):
        if counter > 0:
            print "Je kan alleen getallen en expressies berekenen!"
            input=raw_input("> ")
        else:
            print
            input=raw_input("> ")

        counter=counter+1
        print
        print "je hebt het volgende ingevoerd: ",input

    try:
        print "het resultaat is:", eval(input)
    except EOFError:
        print "EOFError, je calculatie klopt niet."
        input=raw_input("> ")
    print
    print       

    counter=0
Was it helpful?

Solution

Your problem is that you are using eval(), which will try to interpret the expression as a Python expression. Python expressions can raise any number of exceptions, but EOFError is one of the least likely.

Catch Exception instead:

try:
    print "het resultaat is:", eval(input)
except Exception:
    print "Oeps, je calculatie klopt niet."

which is the base class for all 'regular' exceptions.

You can assign the exception to a local name and print out the message with your error message:

try:
    print "het resultaat is:", eval(input)
except Exception as err:
    print "Oeps, je calculatie klopt niet:", err

The better approach would be to parse the expression and perhaps use the functions of the operator module to make the calculations.

The EOFError exception is raised by the raw_input() function when input is closed without any data being received:

>>> raw_input('Close this prompt with CTRL-D ')
Close this prompt with CTRL-D Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
EOFError

Unless you pass a string containing a raw_input() or input() call to the eval() function you will not encounter that exception.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top