[Tutor] Regarding Exceptions

wesley chun wescpy at gmail.com
Fri Feb 21 18:48:40 CET 2014


On Mon, Feb 17, 2014 at 3:29 AM, Khalid Al-Ghamdi <emailkgnow at gmail.com>
wrote:
Hi, in the following snippet, why is it I don't need to create an Exception
object and I can use the class directly in raise my custom exception?

here's a new one... i'm going to try to answer this question without
working code since everyone has pointed out it won't compile. the OP is
simply asking why Exception didn't need to be defined before using, as with
all Python variables... IOW, why doesn't it give a NameError exception here?

the reason is because Exception is a built-in, meaning that it's C code
that's been made available for you before your Python code executes. look:

>>> Exception
<type 'exceptions.Exception'>

in reality, built-ins are part of a magical module called __builtins__
that's "automagically" imported for you so that you never have to do it
yourself. check this out:

>>> __builtins__.Exception
<type 'exceptions.Exception'>

you can also find out what all the other built-ins are using dir():
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError',...]

hope this helps!
--wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"A computer never does what you want... only what you tell it."
    +wesley chun : wescpy at gmail : @wescpy
    Python training & consulting : http://CyberwebConsulting.com
    "Core Python" books : http://CorePython.com
    Python blog: http://wescpy.blogspot.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140221/a59155f8/attachment.html>


More information about the Tutor mailing list