Exception instances
Because your custom Exceptions are classes, you can again use the mighty power of OOP and add custom attributes and methods like you would do for a normal class.
class StupidInputError(Exception):
def __init__(self, input, message="Don't be silly!"):
self.input = input
self.message = message
def print(self):
print(f"Josiah says: {self.message} You have typed a stupid input: {self.input}")
The except
clause can actually also receive the instance of the exception with the as
keyword.
try:
raise StupidInputError("hahaha", "You are silly.")
except StupidInputError as err:
err.print()
print(f"{err.input}")
print(f"{err.message}")
## Josiah says: You are silly. You have typed a stupid input: hahaha
## hahaha
## You are silly.
Of course, the built-in Exception classes should be enough to cover most of your needs. So only create your own custom Exception classes when there is a clear reason to do so.
args attribute
Subclasses of BaseException
(all built-in Exceptions and your custom Exception classes) have an .args
attribute (a tuple
). They store the arguments of the instance of the Exception.
You can also print()
any of these arguments without having to explicitly refer to .args
(BaseException
implements the __str__()
method that returns the arguments automatically as a string).
try:
raise Exception("first", "second", "third")
except Exception as err:
x = err.args
print(type(x))
print(x[0])
print(x[1])
print(x[2])
print(err)
Your tasks:
- Try creating your own custom Exception class with your own attributes
- Try retrieving the arguments using the generic
.args
instead of using a user-defined Exception class