newb: Question regarding custom exception

C

crybaby

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

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: ?
 
S

Steven D'Aprano

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top