I’m working on making a small Python module. I want this module to return errors, if any occur. What is the proper or standard way to create error objects in Python?
Edit: I’m not really sure how to create my own errors, surely because i am not sure how errors work (i just know how to catch them in try: ... except: ...).
So right now i made draft error messages, errors are strings. When something goes unexpected i print the and return None. I guess that’s not the proper way 🙂
Example:
...
self.IsNotStringError = "Args was not a string."
...
def myMethod(self, args)
""" Args must be a string. """
if not isinstance(args, str):
print IsNotStringError
return None
else:
do things...
Edit(bis): On reading the answers below, i have looked further into Python documentation. There is a tutorial on how to make user-defined exceptions.
Example from the documentation:
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
You can create your own exception class by inheriting
Exception:next just raise it whenever you need to: