Domanda

Come posso ottenere il tipo di un'eccezione in Python 1.5.2?

In questo modo:

try:
    raise "ABC"
except Exception as e:
    print str(e)

dà uno SyntaxError:

  except Exception as e:
                    ^

SyntaxError: invalid syntax

Modifica questo non funziona:

try:
    a = 3
    b = not_existent_variable
except Exception, e:
    print "The error is: " + str(e) + "\n"

a = 3
b = not_existent_variable

come ho solo l'argomento, non è l'errore effettivo (NameError):

The error is: not_existent_variable

Traceback (innermost last):
  File "C:\Users\jruegg\Desktop\test.py", line 8, in ?
    b = not_existent_variable
NameError: not_existent_variable
È stato utile?

Soluzione

E '

except Exception, e:

In Python 1 e 2. (Anche se as funziona anche in Python 2.6 e 2.7).

(Perché mai stai usando 1.5.2!?)

Per ottenere quindi il tipo di errore si utilizza type(e). Per ottenere il nome del tipo in Python 2 si utilizza type(e).__name__, non ho idea se funziona in 1.5.2, dovrete controllare i documenti.

Aggiornamento:. Essa non ha, ma ha fatto e.__class__.__name__

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top