Python: How to catch inner exception of exception chain? -


consider simple example:

def f():     try:         raise typeerror     except typeerror:         raise valueerror  f() 

i want catch typeerror object when valueerror thrown after f() execution. possible it?

if execute function f() python3 print stderr raised exceptions of exception chain (pep-3134) like

traceback (most recent call last):   file "...", line 6, in f     raise typeerror typeerror  during handling of above exception, exception occurred:  traceback (most recent call last):   file "...", line 11, in <module>     f()   file "...", line 8, in f     raise valueerror valueerror 

so list of exceptions of exception chain or check if exception of type (typeerror in above example) exists in exception chain.

python 3 has beautiful syntactic enhancement on exceptions handling. instead of plainly raising valueerror, should raise caught exception, i.e.:

try:     raise typeerror('something awful has happened') except typeerror e:     raise valueerror('there bad value') e 

notice difference between tracebacks. 1 uses raise from version:

traceback (most recent call last):   file "/home/user/tmp.py", line 2, in <module>     raise typeerror('something awful has happened') typeerror: awful has happened  above exception direct cause of following exception:  traceback (most recent call last):   file "/home/user/tmp.py", line 4, in <module>     raise valueerror('there bad value') e valueerror: there bad value 

though result may seem similar, in fact rather different! raise from saves context of original exception , allows 1 trace exceptions chain - impossible simple raise.

to original exception, have refer new exception's __context__ attribute, i.e.

try:     try:         raise typeerror('something awful has happened')     except typeerror e:         raise valueerror('there bad value') e except valueerror e:     print(e.__context__) >>> awful has happened 

hopefully solution looking for.

for more details, see pep 3134 -- exception chaining , embedded tracebacks


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -