2012-09-23 70 views
12

¿Hay alguna manera de usar los atributos/propiedades de un objeto de excepción en un bloque try-except en Python?¿Cómo usar los atributos de una Excepción en Python?

Por ejemplo en Java tenemos:

try{ 
    // Some Code 
}catch(Exception e){ 
    // Here we can use some of the attributes of "e" 
} 

Lo equivalente en Python me daría una referencia a 'e'?

+17

Por qué las estrechas votos? Esta es una pregunta bastante legítima. –

+0

Estoy de acuerdo. La pregunta es extrañamente vaga. Es casi como "¿Cómo escribo Python"? – Aaron

+0

Yo tampoco entiendo la moderación de "no es una pregunta real". La pregunta es muy específica, y Ashwini Chaudhary dio una buena respuesta. –

Respuesta

34

Usa la instrucción as. Puede leer más sobre esto en Handling Exceptions.

>>> try: 
...  print(a) 
... except NameError as e: 
...  print(dir(e)) # print attributes of e 
... 
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', 
'__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', 
'__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__traceback__', 'args', 
'with_traceback'] 
6

Claro, hay:

try: 
    # some code 
except Exception as e: 
    # Here we can use some the attribute of "e" 
7

Aquí se muestra un ejemplo de la docs:

class MyError(Exception): 
    def __init__(self, value): 
     self.value = value 

    def __str__(self): 
     return repr(self.value) 

try: 
    raise MyError(2*2) 
except MyError as e: 
    print 'My exception occurred, value:', e.value 
Cuestiones relacionadas