[Tutor] Exception Handling and Stack traces

Peter Otten __peter__ at web.de
Fri Sep 10 15:56:51 CEST 2010


Michael Powe wrote:

> I can't work out how to suppress stacktrace printing when exceptions
> are thrown.

[snip rant]

It might have been a good idea to read a tutorial like

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

or ask before you got annoyed enough to write that rant ;)

To catch an exception you have to put the class into the except clause, not 
an instance. Basic example, using 2.6 syntax:

WRONG:

>>> try:
...     1/0
... except ZeroDivisionError("whatever"):
...     print "caught"
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero

CORRECT:

>>> try:
...     1/0
... except ZeroDivisionError as e:
...     print "caught", e
...
caught integer division or modulo by zero

Peter



More information about the Tutor mailing list