From: Payal on
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?
what does the word "as" do?

Thanks a lot in advance.
With warm regards,
-Payal
--


From: Chris Rebert on
On Thu, Jun 3, 2010 at 11:31 PM, Payal <payal-python(a)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
From: Payal on
On Thu, Jun 03, 2010 at 11:42:16PM -0700, Chris Rebert wrote:
> >>> try:
> ... x[1]
> ... except IndexError as e:
> ... print "Got error:", e.args[0] # grab the error message
> ...
> Got error: list index out of range

Thanks a lot. This example solved what the tutorial could not.

With warm regards,
-Payal
--