queries about exceptions(newbie)

Chris Rebert clp2 at rebertia.com
Fri Jun 4 02:42:16 EDT 2010


On Thu, Jun 3, 2010 at 11:31 PM, Payal <payal-python at scriptkitchen.com> wrote:
> Hi all,
> I am trying to learn exceptions and have few small doubts from
> http://docs.python.org/tutorial/errors.html
> There are many statements there of the form,
>
> ... except Exception as inst:
>        do something
>
> ... except ZeroDivisionError as detail:
>        do something
>
> ... except MyError as e:
>        do something
>
> My questions are,
> what are these "inst", "detail", "e" etc. Are they special words?

No, just arbitrary variable names.

> what does the word "as" do?

If there's an exception of the specified type, the instanciated
exception object will be bound to the specified variable before the
body of the `except` statement executes. "as" is used when you want to
inspect/manipulate the exception that was thrown. For example:

>>> x = []
>>> x[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>>
>>> try:
...     x[1]
... except IndexError as e:
...     print "Got error:", e.args[0] # grab the error message
...
Got error: list index out of range

If you don't care about the actual exception object, you can of course
omit the "as" part of the except clause.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list