[Tutor] try and except

Lie Ryan lie.1296 at gmail.com
Tue Dec 29 22:29:42 CET 2009


On 12/30/2009 7:47 AM, Grigor Kolev wrote:
> Hi.
> Can someone explain me where is my mistake.
> -----------------------------------------------
> class Error(Exception):
> 	def printer(self , value ):
> 		self.value = value
> 		print self.value
> def oops():
> 	raise Error
> def domoed():
> 	try:
> 		oops()
> 	except Error:
> 		Test = Error()
> 		print 'Error: ', Test.printer('Test')
> 	else:
> 		print 'no error'
> if __name__ == "__main__":
> 	domoed()
> ------------------------------------------------------
> Result is:
> Error:  Test
> None
>> From where come it None

Test.printer(...) returns "None" and when you:

print 'Error: ', Test.printer('Test')

turns to:

print 'Error: ', None

And rather your approach seems "unconventional". You shouldn't create a 
new Exception object in the except-clause unless you want to raise that 
new exception.

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

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

def domoed():
     try:
         oops()
     except Error, e:
         e.printer()
     else:
         print 'no error'
if __name__ == "__main__":
     domoed()



More information about the Tutor mailing list