Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Exceptions in Python (a few things you may not now)

Exceptions in Python (a few things you may not now)

Lightning talk first given at the SF Python Meetup on 5/8/13.

Brian Rue

May 08, 2013
Tweet

Other Decks in Programming

Transcript

  1. Logging: log.exception() >>> import logging >>> logging.basicConfig() >>> log =

    logging.getLogger(__name__) >>> >>> try: ... foo = bar ... except: ... log.exception("Something went wrong") ... # or: log.error("Uh oh", exc_info=True) ... ERROR:__main__:Something went wrong Traceback (most recent call last): File "<stdin>", line 2, in <module> NameError: name 'bar' is not defined
  2. Under the hood: sys.exc_info() >>> import sys >>> >>> try:

    ... foo = bar ... except: ... type, value, tb = sys.exc_info() ... print "Exception class:", cls ... print "Exception instance:", exc ... print "Traceback instance:", tb ... Exception class: <type 'exceptions.NameError'> Exception instance: name 'bar' is not defined Traceback instance: <traceback object at 0x10802f8c0>
  3. The traceback module import sys, traceback def do_something(): foo =

    bar try: do_something() except: type, value, tb = sys.exc_info() print traceback.extract_tb(tb) $ python slide4.py [('slide4.py', 7, '<module>', 'do_something()'), ('slide4.py', 4, 'do_something', 'foo = bar')]
  4. sys.excepthook >>> import sys >>> >>> def my_excepthook(type, value, traceback):

    ... print "Got an exception!" ... print type, value, traceback ... ... >>> sys.excepthook = my_excepthook >>> >>> foo = bar Got an exception! <type 'exceptions.NameError'> name 'bar' is not defined <traceback object at 0x10d619950>
  5. Gotcha: return from try-finally >>> def main(): ... try: ...

    print "trying..." ... foo = bar ... except: ... print "excepting..." ... bar = baz ... finally: ... print "finally..." ... return ... >>> main() trying... excepting... finally...
  6. Better: return outside of finally >>> def main(): ... try:

    ... print "trying..." ... foo = bar ... except: ... print "excepting..." ... bar = baz ... finally: ... print "finally..." ... return ... >>> main() trying... excepting... finally... Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 7, in main NameError: global name 'baz' is not defined