0

I am relatively new to Python and I am trying to learn a thing or two about classes. I have some experience with functions and I am trying to understand how classes work. My question is about error handling.

Normally with a function, I can perform some operations and if something goes wrong, I can simply return False and validate it where the function's been called before moving on with the rest of the code execution.

How can I do this with the classes?

I have a simple class with a simple method, say:

my_object = MyObj()
my_object.swim()

When I make my_object "swim", I want to be able to handle errors or problems, in a simple manner. For example:

During the execution of def swim(..): I want to be able to return False or raise different errors and handle them without interrupting the application completely.

I.e. I want to:

try:
    my_object.swim()
except:
    # it can not swim. I want it to tell me why or just tell me "False" so I can execute another codeblock and tell it to perhaps .walk_away()

I read about try/except blocks, raising errors, how they are classes. But it does not do what I like, which is to try performing a method and handling the results of that method's execution (true, false or another error, perhaps?)

How can I do this in Python?

Thank you.

Phil
  • 13,875
  • 21
  • 81
  • 126
  • 1
    If you prefer handling errors by returning false, why not just continue doing that? There's nothing particular about classes or OO that says you cannot return a success code from a method. – hmakholm left over Monica Oct 27 '12 at 22:04
  • because I don't want to assign return of my method to a name-variable and than validate it. I want to try: except: especially since this method can generate errors with different codes, not just a positive or negative. – Phil Oct 27 '12 at 22:05
  • But that doesn't seem to have anything in particular to do with the fact that swim() is a method rather than a plain old function. – hmakholm left over Monica Oct 27 '12 at 22:06

2 Answers2

5

You would do the following:

class MayNotSwimException(Exception):
    def __init__(reason):
        self.reason = reason

class Person(object):
    def __init__(self, can_swim):
        self.can_swin = can_swim

    def swim(self):
        if self.can_swim:
            self.do_something()
        else:
            raise MayNotSwimException("I can't swim because...!")

    def walk_away(self):
        self.do_something_else()



p = Person(can_swim = False)
try:
    p.swim():
except MayNotSwimException as e: # In python 2.5-, use MayNotSwimException, e 
    print "That person can't swim because", e.reason
    p.walk_away()

Exceptions can be used to:

  • Alter the flow of control (jump back to a try/except block)
  • Transfer information through the exception itself. This can be achieved by raising different types of Exceptions (ie. We could define a MayNotSwimBecauseDoesntWantException and a MayNotSwimBecauseFeelsSleepyException and catch them separately) or through attributes of the Exception object itself (e.reason).

Please have a look at the documentation for a more detailed explanation!

Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116
  • 1
    [Shouldn't that be `except MayNotSwimException as e`](http://stackoverflow.com/q/2535760/102441)? – Eric Oct 27 '12 at 22:24
  • @Eric Well, `, e` is valid in python 2.x, but you're right in saying that it's not python's greatest achievement in syntax clarity. I'll update! – Thomas Orozco Oct 27 '12 at 22:28
2

Put the try..except or other form of checking for failure (and the reaction code) in the swim method itself. Exceptions need not be fatal, but I suggest you limit their use where normal conditionals can be used, to keep the code clean.

lynxlynxlynx
  • 1,371
  • 17
  • 26