Problems trying to hook own exception function to sys.excepthook

Peter Otten __peter__ at web.de
Sun Apr 6 05:26:35 EDT 2008


Sami wrote:

> Hello,
> 
> I am new to Python.
> 
> I tried to hook my own ExceptionPrintingFunction sys.excepthook but it
> does not work.
> 
> This is what I wrote:
> -----------------------------------------------------------------------
> import sys
> 
> def MyOwnExceptHook(typ, val, tb):
> print "Inside my own hook"
> 
> sys.excepthook = MyOwnExceptHook
> 
> x = 1/0
> -----------------------------------------------------------------------
> This is what I get
> -----------------------------------------------------------------------
> Traceback (most recent call last):
>    File
> "E:/Home/Programming/Python/TryProjects/ExceptHandling1/Except5.py",
> line 8, in <module>
>      x = 1/0
> ZeroDivisionError: integer division or modulo by zero
> -----------------------------------------------------------------------
> 
> I never see "Inside my own hook" which tells me that the hook is not
> being called. What I really want to test is to stop the exception from
> propagating further and leave the program intact.
> 
> What am I doing wrong? Please let me know if there are any other newbie
> groups that I should probably try in stead.

Are you running your code from within idle? It wraps your script in
something like

try:
   # run script
except:
   # show traceback

(Have a look at InteractiveInterpreter.runcode() in code.py if you are
interested in the actual code) 

So your except hook never gets to see the exception and therefore won't be
invoked. Run your script from the commandline and you will see the
behaviour you expected.

Peter




More information about the Python-list mailing list