newb: Question regarding custom exception

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Sep 23 09:52:17 EDT 2007


On Sun, 23 Sep 2007 05:32:28 -0700, crybaby wrote:

> Why you specify type and name of the exception in your custom
> exceptions,
> but not in built in exceptions
>     except IOError:
>         print "no file by the name ccy_rates*.txt"
> 
>     except MyError, e:
>                 print e.msg

You can say:

except IOError, e:
    print e.msg


And you can say:

except MyError:
    print "whatever I want"


It all depends on what you want to do.


 
> Also, when you do:
> 
> try: raise MyError(23)
> 
> In "try: MyError(23) ", you are calling MyError class, but actually get
> instantiated in except MyError, e: ?

I don't understand what you are actually asking, but I will try my best.


raise MyError(23)

calls the class MyError and creates and instance, and that instance is 
then used as an argument to the raise statement. You can also do this:

instance = MyError(23)
raise instance    

You don't need the try block unless you want to catch the exception. The 
exception itself it actually raised by the "raise" statement, not the 
"except" statement. The "except" statement _catches_ the exception.

Try typing these lines in the interactive interpreter:



try:
    print "before the exception"
    raise Exception("an error occurred")
    print "this line is never executed"
    print "neither is this"
except Exception, e:
    print "the exception is:"
    print e
    print e.message





Hope this helps.



-- 
Steven.



More information about the Python-list mailing list