[Tutor] try and except

Dave Angel davea at ieee.org
Thu Dec 31 15:58:33 CET 2009


spir wrote:
> 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
>
>   
The __str__() method needs to return a string, not print it.  And it 
doesn't take a "value" argument.  I think you want (untested):

       def __str__(self):
             return 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