[Tutor] Universal error handler

Kent Johnson kent37 at tds.net
Tue Jun 20 18:02:09 CEST 2006


Matti Niemelä wrote:
> Hi!
> 
> Just started learning Python, and I was wondering if there is a way to 
> catch an error or errors (like EOFError) whenever it occures during the 
> script? The script (the program) wouldn't have any handling for that 
> error itself, but a seperate block would handle that at the start or the 
> end of the file.

For beginners, often the best solution is not to catch the errors at 
all, but let the runtime catch it and give you a stack trace and error 
message. This is much better than catching it yourself and printing a 
generic error message because it will show you exactly where and what 
the error is. It is also much easier to get help here if you have a 
stack trace to show.

If you really want to trap the errors, your approach below is fine, 
there is nothing wrong with encapsulating your main code in a function. 
The more code you have the more likely that this is a reasonable way to 
structure the code anyway.

OK, if you really have to have a global way to configure the error 
handler, look at sys.excepthook. This lets you install your own error 
handler for uncaught exceptions. If the docs are completely confusing, 
you probably shouldn't be using it... :-)

Kent
> 
> For a simple 200 line script I made the whole thing into a function, and 
> at the end put:
> 
> def main():
>      # Do the program itself..
> 
> # The very end
> try:
>      main()
> except EOFError:
>      # Tell something went horribly wrong
> 
> 
> I find this way of doing it disfunctional when having lots of code. Any 
> ideas?



More information about the Tutor mailing list