[Python-Dev] PEP 8: mention bare 'except:'

A.M. Kuchling amk at amk.ca
Fri Dec 22 14:05:47 CET 2006


http://www.python.org/sf/411881 is a bug about removing use
of 'except:' in stdlib code.  In many cases the intent is to catch
one particular exception such as ImportError or AttributeError,
but catching all exceptions can disguise other problems.

Should PEP 8 mention this issue?  Here's some proposed text for
discussion:

 - When catching exceptions, mention specific exceptions
   whenever possible instead of using a bare 'except:' clause.

   For example, use::

       try:
           import platform_specific_module
       except ImportError:
           platform_specific_module = None 

   A bare 'except:' clause will catch SystemExit and KeyboardInterrupt
   exceptions, making it harder to interrupt a program with Control-C,
   and can disguise other problems.  If you want to catch all
   exceptions that signal program errors, use 'except StandardError:'.

   A good rule of thumb is that you should only use 'except:' if the
   exception handler will be printing out or logging the traceback; at
   least the user will be aware that an error has occurred.

--amk


More information about the Python-Dev mailing list