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
  • 6,976
  • 5
  • 30
  • 53
Bwire
  • 1,151
  • 1
  • 15
  • 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
  • 8,558
  • 5
  • 25
  • 26
thefourtheye
  • 221,210
  • 51
  • 432
  • 478
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
  • 17,799
  • 3
  • 45
  • 59