17

I'm trying to write a simple exception handling. However it seems I'm doing something wrong.

def average():
    TOTAL_VALUE = 0
    FILE = open("Numbers.txt", 'r')

    for line in FILE:
        AMOUNT = float(line)
        TOTAL_VALUE += AMOUNT
        NUMBERS_AVERAGE = TOTAL_VALUE / AMOUNT
    print("the average of the numbers in 'Numbers.txt' is :",
        format(NUMBERS_AVERAGE, '.2f')) 

    FILE.close()

    except ValueError,IOError as err:
        print(err)

average()

> line 14
>         except ValueError as err:
>              ^
>     SyntaxError: invalid syntax
3
  • 2
    The code and the exception you show are at odds with one another. To be able to help you, we need to see the actual code and the actual exception, not some approximations. Commented Nov 18, 2013 at 21:03
  • 1
    And please don't use CAPITALS except for constants. None of those variables you use are constants. Commented Nov 18, 2013 at 21:08
  • This is the actual code and the actual exception. Commented Nov 18, 2013 at 21:11

1 Answer 1

23

There are two things wrong here. First, You need parenthesis to enclose the errors:

except (ValueError,IOError) as err:

Second, you need a try to go with that except line:

def average():
    try:
        TOTAL_VALUE = 0
        FILE = open("Numbers.txt", 'r')

        for line in FILE:
            AMOUNT = float(line)
            TOTAL_VALUE += AMOUNT
            NUMBERS_AVERAGE = TOTAL_VALUE / AMOUNT
        print("the average of the numbers in 'Numbers.txt' is :",
            format(NUMBERS_AVERAGE, '.2f')) 

        FILE.close()

    except (ValueError,IOError) as err:
        print(err)

except cannot be used without try.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.