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?

Mad Dog Tannen
  • 7,129
  • 5
  • 31
  • 55
Bwire
  • 1,181
  • 1
  • 14
  • 25

2 Answers2

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.

quornian
  • 9,495
  • 6
  • 30
  • 27
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
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

James Mills
  • 18,669
  • 3
  • 49
  • 62