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.