Best Way to Handle All Exceptions
Ben Finney
ben+python at benfinney.id.au
Mon Jul 13 20:09:06 EDT 2009
seldan24 <seldan24 at gmail.com> writes:
> I'm fairly new at Python so hopefully this question won't be too
> awful. I am writing some code that will FTP to a host, and want to
> catch any exception that may occur, take that and print it out
> (eventually put it into a log file and perform some alerting action).
You have been given a lot of advice so far about catching exceptions
with the ‘try … except’ syntax. But reading your request, I think
perhaps you don't want to catch exceptions at all.
Instead of catching *all* exceptions at a specific point in your code,
and then having nothing to do but end the program (possibly after some
pre-exit action like logging), I think you would be better served by
installing a custom top-level exception handler.
When an exception is raised and uncaught, the interpreter calls
sys.excepthook with three arguments, the exception class, exception
instance, and a traceback object. In an interactive session this
happens just before control is returned to the prompt; in a Python
program this happens just before the program exits. The handling of
such top-level exceptions can be customized by assigning another
three-argument function to sys.excepthook.
<URL:http://docs.python.org/library/sys#sys.excepthook>
With a custom top-level exception handler in place, you should then
restrict your use of ‘try: … except FooException: …’ to be as precise
as possible, so that the ‘try’ block is as small as possible and the
‘FooException’ is as specific as possible.
Any other exceptions that you don't specifically catch will then go
through to your default handle-it-just-before-we-exit ‘sys.excepthook’
exception handler.
--
\ “Nature hath given men one tongue but two ears, that we may |
`\ hear from others twice as much as we speak.” —Epictetus, |
_o__) _Fragments_ |
Ben Finney
More information about the Python-list
mailing list