global exception catching

Duncan Booth duncan at
Thu Feb 27 10:41:40 CET 2003

"Hilbert" <hilbert at> wrote in 
news:v5raufd60iu1ba at

> Hello,
> Is there a way to catch a "global" exception in a python
> program (meaning that if there would be an error
> during execution it could call a function before exiting)?
> I have a program that creates large temp files and in case
> of any unforseen problems I still need to clean up before
> exiting.
Option 1:
Put your code inside a try ... except block. This is usually the best 
option since it is obvious what the code is doing, and it gives you the 
option to change your cleanup code by having multiple exception blocks 
(e.g. you probably don't want to delete temp file before you have finished 
initialisation or after you have already deleted them on termination).

Option 2:
Hook into sys.excepthook. This means you don't have to write an exception 
handler round all your code, which could be useful if you needed cleanup 
for exceptions raised outside what you would consider the normal part of 
the code.

You don't say what OS you are running on, so be aware that neither of these 
will properly handle Ctrl-Break on Windows. If you need to handle Ctrl-
Break then (provided you are using Python 2.2 or later) you have to install 
a SIGBREAK handler. e.g. 

    signal.signal(signal.SIGBREAK, signal.default_int_handler)

This would make Ctrl-Break raise KeyboardInterrupt instead of its default 
action which is to terminate your Python program without doing any cleanup.
If your application does anything with network sockets then these will 
interact badly with a SIGBREAK handler (you might need multi-threading to 
handle this effectively).

Duncan Booth                                             duncan at
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?

More information about the Python-list mailing list