4

I am just being curious about the syntax of python exceptions as I can't seem to understand when you are suppossed to use the syntax below to catch an exception.

try:
    """
      Code that can raise an exception...
    """
 except Exception as e:
     pass

and

try:
    """
      Code that can raise an exception...
    """
 except Exception, e:
     pass

What is the difference?

1
  • I guess I wasn’t keen thanks @MartijnPieters Commented Dec 14, 2013 at 11:38

2 Answers 2

4

Note: As Martijn points out, comma variable form is deprecated in Python 3.x. So, its always better to use as form.

As per http://docs.python.org/2/tutorial/errors.html#handling-exceptions

except Exception, e:

is equivalent to

except Exception as e:

Commas are still used when you are catching multiple exceptions at once, like this

except (NameError, ValueError) as e:

Remember, the parentheses around the exceptions are mandatory when catching multiple exceptions.

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

5 Comments

Except that the latter is preferred, the former deprecated and completely removed in Python 3.
Your last line shows why as was introduced to replace the comma. It was confusing as hell when multiple exceptions were being caught. Use except (NameError, ValueError) as e: there.
@MartijnPieters Got you :) Updated it
It was common to write the latter as except NameError, ValueError: and wonder why it didn't work, or use except (NameError, e): and wonder why you still got a NameError on e.
You are still implying that you can only catch multiple exceptions with the now-deprecated syntax.
1

except Exception, e is deprecated in Python 3.

The proper form is:

try:
    ...
except Exception as e:
    ...

See: http://docs.python.org/3.0/whatsnew/2.6.html#pep-3110

1 Comment

The comma form is not just deprecated in Python 3; it is removed altogether.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.