I am doing some exercises with exceptions created by me in Python but I did not quite understand this part of attributes in exceptions. I wanted that when the code fell into the exception, it would show a certain argument. How do I do this?
I am doing some exercises with exceptions created by me in Python but I did not quite understand this part of attributes in exceptions. I wanted that when the code fell into the exception, it would show a certain argument. How do I do this?
I do not know if I understand your question right, but exception classes in python can use the same builder mechanisms, attributes, properties, and methods as any other class can. So maybe you want to do something like this:
class MinhaExcecao(Exception):
def __init__(self, valor):
self.__valor = valor
@property
def valor(self):
return self.__valor
def alguma_funcao():
raise MinhaExcecao(42)
def outra_funcao():
try:
alguma_funcao()
except MinhaExcecao as e:
print(e.valor)
outra_funcao()
Note that e
in block except
is a variable that contains a reference to MinhaExcecao
. That way, you can use all the methods, properties, and attributes that MinhaExcecao
offers to do what you need. In particular, this is very useful for carrying detailed information about an error / exception from its source to the point where it is handled.