Sabri Gül
Sabri Gül

Reputation: 155

How to fix invalid syntax error at 'except ValueError'?

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

Upvotes: 17

Views: 61192

Answers (1)

user2555451
user2555451

Reputation:

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.

Upvotes: 23

Related Questions