2
I’m doing some exercises with exceptions created by me in Python but I don’t really understand this part of attributes in exceptions. I wanted when the code fell on Exception, it would show a certain argument. How do I do this?
2
I’m doing some exercises with exceptions created by me in Python but I don’t really understand this part of attributes in exceptions. I wanted when the code fell on Exception, it would show a certain argument. How do I do this?
3
I don’t know if I got your question right, but exception classes in python can use the same constructor mechanisms, attributes, properties and methods that any other classes can also. So maybe you want to do something kind of 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 the e
in the block except
is a variable containing a reference to MinhaExcecao
. Therefore, you can use all methods, properties and attributes that MinhaExcecao
offers to do whatever you need. In particular, this is very useful to carry detailed information about an error/exception of its origin to the point where it is treated.
0
It’s very simple, you can Print something or even return a JSON.
try:
return bla
except Exception as ex:
# print "Sua mensagem" # ou
return algo
See also the documentation: 2.7 https://docs.python.org/2/tutorial/errors.html
or in 3.7 https://docs.python.org/3/tutorial/errors.html
Good study!
Browser other questions tagged python exception
You are not signed in. Login or sign up in order to post.