2

Does python have a "catch all" solution where if an error/exception is triggered anywhere in the script the error is passed to a custom function similar to how PHP's set_error_handler() function works?

I'm familiar with the try/catch method, but it's kind of a nuissance since the try/catch only works on the immediate code within in it.

def sample_function():
    # some code that causes error, breaks script, does not pass error back to try/catch

try:
    sample_function()
except Exception, e: 
    print str(e)

I'm looking for a simple try/except everything even if error is triggered within a function called from within a function without having to wrap every block of code with a try/except.

Does anyone know if this is possible?

Joe
  • 1,710
  • 8
  • 39
  • 60
  • 1
    @Nix -- Blast! And I was all proud of myself for digging `sys.excepthook` out of the documentation. I thought to myself, "Surely I'll get some upvotes for this one" – mgilson Jan 31 '13 at 18:33
  • @mgilson i gave you some love.. but it is a dupe :) – Nix Jan 31 '13 at 18:34
  • thanks guys, while searching for previous answers, should have added "global"! – Joe Jan 31 '13 at 18:36

2 Answers2

3

Somewhere in your code is the main entry point. Just wrap the try/except around that.

XORcist
  • 4,188
  • 21
  • 31
1

It looks to me like you can assign a 3 argument function to sys.excepthook

mgilson
  • 283,004
  • 58
  • 591
  • 667