How to display the attributes of an Exception in Python?

Asked

Viewed 102 times

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 answers

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.

See here working on ideone.

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.