Skip to content

Instantly share code, notes, and snippets.

@babo
Created November 12, 2013 16:03
Show Gist options
  • Save babo/7433428 to your computer and use it in GitHub Desktop.
Save babo/7433428 to your computer and use it in GitHub Desktop.
how to re-raise an exception with proper stack information
#!/usr/bin/env python
import sys
import traceback
def f(x):
a = x / 0
return a
def g():
a = {}
print a[42]
def h():
try:
f(12)
except Exception:
saved_info = sys.exc_info()
print 'Exception of type ', saved_info[0]
try:
g()
except Exception:
print 'An exception during exception handling'
raise saved_info[0], saved_info[1], saved_info[2]
def main():
try:
h()
except Exception:
saved_info = sys.exc_info()
print 'in main'
traceback.print_tb(saved_info[2])
if __name__ == '__main__':
main()
@aorcsik
Copy link

aorcsik commented Nov 12, 2013

But if I want something like this:

1|  try:
2|      f(12)
3|  except TheExceptionIWantToHandle:
4|      handle_it()
5|  except Exception:
6|      saved_info = sys.exc_info()
7|      raise saved_info[0], saved_info[1], saved_info[2]

This is nicer, right?

5|  except Exception:
6|      raise

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment