1

I noticed that exceptions that are handled do not result in a call to sys.excepthook... which makes sense in retrospect.

But, how do I log or otherwise customize the way that handled exceptions are dealt with? When this code executes...

try:
    1/0
except:
    pass

I would like to be able to log the fact that a ZeroDivisionError was handled.

Is there a way to do this?

JacobIRR
  • 8,545
  • 8
  • 39
  • 68

1 Answers1

0

You can get the Exception and print info about it or log that with a logging call of your own:

try:
  1/0
except Exception, e:
  print("a {0} was not raised".format(e.__class__.__name__))
  # or logging.yourLogger(e.__class__.__name__)
  pass

Result:

a ZeroDivisionError was not raised

If you were looking for some kind of Global Exception Handling, that is probably not trivial or not possible without enclosing everything in try/except.

JacobIRR
  • 8,545
  • 8
  • 39
  • 68
  • Ah. Yeah, I was looking for a global solution. Bummer. I'm dealing with a gigantic codebase where `try/except` is abused all over the place. The root cause is often silenced in places where it should not be. Thanks for your response. – user9132884 Feb 27 '18 at 05:52
  • It looks like it might be possible with https://docs.python.org/2/library/sys.html#sys.settrace ...maybe just intercept 'exception'? I'll post here if results are interesting. – user9132884 Feb 27 '18 at 06:00