bluethundr
bluethundr

Reputation: 1325

Python invalid syntax for try/except

I'm trying to create an exception based on whether or not a file has been removed:

def remove_file():
    print("Removing the output file: ", output_file)
    try:
        os.remove(output_file)
    except RemoveFileError,e:
        remove_stat = e.returncode
    if remove_stat == 0:
        print("File Removed!")

But I'm getting the following error:

  File ".\aws_ec2_list_instances.py", line 198
    except RemoveFileError,e:
                          ^
SyntaxError: invalid syntax

I thought I could call the exception whatever I wanted. Is that not the case? How can I write this correctly?

Upvotes: 0

Views: 111

Answers (1)

Guybrush
Guybrush

Reputation: 2780

Which version of Python are you using? Because the syntax has changed between Python 2 and Python 3.

In Python 2, it's (mostly) except Exception, var: where it is except Exception as var: in Python 3.

Notice that Python 3 syntax was backported to Python 2.6 and 2.7, so it is not unusual to see except Exception as var in those versions (and this should be preferred if you want this specific piece of code to work on both Python 2.6+ and 3+).

Upvotes: 1

Related Questions