How to display the attributes of an Exception in Python?

2

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?

    
asked by anonymous 21.10.2018 / 01:42

2 answers

3

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.

See here working on ideone.

    
21.10.2018 / 02:05
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 in the documentation: 2.7 link

or in the link

Good study!

    
21.10.2018 / 02:03