[Tutor] try and except

spir denis.spir at free.fr
Wed Dec 30 14:39:52 CET 2009


Lie Ryan dixit:

> class Error(Exception):
>      def __init__(self, value):
>          self.value = value
>      def printer(self, value):
>          print self.value

You can also use __str__ instead of printer. This will give a standard output form for your error automatically used by print and also, for exceptions, when python writes it to stderr: you don't need to catch the error to write it yourself.

     def __str_(self, value):
         print self.value

So that a test case may be (untested):

def oops():
     raise Error('some error')

def domoed(catch_error_and_go_on = False):
    if catch_error_and_go_on:
        try:
            oops()
        except Error, e:
            print e	# just for feedback
        else:
            print 'no error'
    else:
        oops()		# will print error
if __name__ == "__main__":
     print "=== case error uncatched"
     domoed()
     print "\n=== case error catched"
     domoed(true)


Denis
________________________________

la vita e estrany

http://spir.wikidot.com/


More information about the Tutor mailing list