2014-06-25 17 views
8

Sto cercando di catturare un'eccezione e sollevare un errore più specifico in un punto nel mio codice:eccezione Raise a eccezione di blocco e reprimere primo errore

try: 
    something_crazy() 
except SomeReallyVagueError: 
    raise ABetterError('message') 

Questo funziona in Python 2, ma in Python 3 , mostra entrambe le eccezioni:

Traceback(most recent call last): 
... 
SomeReallyVagueError: ... 
... 

During handling of the above exception, another exception occurred: 

Traceback(most recent call last): 
... 
ABetterError: message 
... 

c'è qualche modo per aggirare il problema, in modo che non viene mostrato traceback SomeReallyVagueError s'?

risposta

13

Nelle versioni di Python 3.3 e superiori, è possibile utilizzare la sintassi raise <exception> from None per sopprimere il traceback della prima eccezione:

>>> try: 
...  1/0 
... except ZeroDivisionError: 
...  raise ValueError 
... 
Traceback (most recent call last): 
    File "<stdin>", line 2, in <module> 
ZeroDivisionError: division by zero 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "<stdin>", line 4, in <module> 
ValueError 
>>> 
>>> 
>>> try: 
...  1/0 
... except ZeroDivisionError: 
...  raise ValueError from None 
... 
Traceback (most recent call last): 
    File "<stdin>", line 4, in <module> 
ValueError 
>>> 
+0

Ciò richiede 3.3 o successiva. –

+0

Ha funzionato! L'ho appena inserito in un'istruzione 'exec' perché il mio codice deve essere eseguito in Python 2 e 3. – refi64

+0

Il' raise da 'è stato aggiunto in 3.0, ma la parte' from None' di quella sintassi non lo ha reso fino a 3.3 come parte di [PEP 409] (https://docs.python.org/3.3/whatsnew/3.3.html#pep-409-suppressing-exception-context). –