[Tutor] try and except

Hugo Arts hugo.yoshi at gmail.com
Tue Dec 29 22:17:28 CET 2009

On Tue, Dec 29, 2009 at 9:47 PM, Grigor Kolev <grigor.kolev at gmail.com> 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

The line "print 'Error: ', Test.printer('Test')" is where it goes
wrong. You should follow closely the execution of this statement:

*  print 'Error: ',

The string "Error: " is printed to the screen. There is a comma, so
the next time something prints, it will be on the same line.

*  Test.printer('Test')

Still on the same line, so the print statement will print the return
value of this function. To do that, we need to execute the function

*  self.value = value
   print self.value

the second statement will result in the string 'Test' being printed to
the screen, on the same line as what was previously printed (because
of our comma earlier). There is no comma here, so the next thing that
is printed will be on a new line.

* Test.printer('Test')

The function is now done executing. What did it return? well, there
was no return statement in the function, so it returned nothing.
Nothing in python is written as 'None.' So, None is printed to the

To fix this, you could either make sure the return value is not
printed, like so:

print 'Error: ',

or, make the printer function a 'returner' function, like so:

def returner(self , value ):
    self.value = value
    return self.value

In general, the 'returner' function is preferable, since it is more
general and thus more flexible.


More information about the Tutor mailing list