one more exception newbie query

Chris Rebert clp2 at rebertia.com
Fri Jun 4 06:22:35 EDT 2010


On Fri, Jun 4, 2010 at 3:10 AM, Payal <payal-python at scriptkitchen.com> wrote:
> Hi all,
> In http://docs.python.org/tutorial/errors.html#handling-exceptions it
> says,
>
> | >>> try:
> | ...    raise Exception('spam', 'eggs')
>
> Why would I want to use a class for exception? I could simply use raise
> w/o it?

`raise Foo, "whatever"` and `raise Foo("whatever")` do the same thing;
the former is deprecated though as it's been removed from Python 3.x

> Also the help() says,
> class Exception(BaseException)

That's *not* a constructor method signature. It's a class declaration
saying Exception is a subclass of the class BaseException.

> But we have used 'spam' and 'eggs'. Why?
>
> | ... except Exception as inst:
>
> Now what does "as inst" do here? (Is it making an instance, but how?
> Aren't instances made with this, inst = Klass() ?)

It's as I explained it before. Another example:

>>> class FooError(BaseException):
...     def __init__(self, x):
...         self.x = x
...
>>> try:
...     raise FooError(42)
... except FooError as e:
...     print "x =", e.x
...
x = 42

The "e" from the "as" is the FooError exception that was raise-d.

I would suggest addressing further questions to the newbie-specific
Python mailinglist, python-tutor:
http://mail.python.org/mailman/listinfo/tutor

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



More information about the Python-list mailing list