# HG changeset patch # User Olivier Delalleau # Date 1314898502 14400 # Node ID 3d4615ee96a4fa0772a38bd4b7d4a29527f2ecd0 # Parent 8be8cdde97ee4199ae119ec8bfa2f984ccfbf0b8 Added recommendation to use "except Exception:" rather than "except:" diff -r 8be8cdde97ee -r 3d4615ee96a4 doc/v2_planning/API_coding_style.txt --- a/doc/v2_planning/API_coding_style.txt Wed Jul 27 13:27:00 2011 -0400 +++ b/doc/v2_planning/API_coding_style.txt Thu Sep 01 13:35:02 2011 -0400 @@ -277,6 +277,23 @@ n_samples_per_split = n_samples / n_splits mean_x = sum(x) / len(x) + * If you really have to catch all exceptions, in general you should use + ``except Exception:`` rather than ``except:``, as the latter also catches + interrupts like when hitting Ctrl-C. + + .. code-block:: python + + # Good (assuming you *must* be catching all exceptions). + try: + someting_that_may_fail_in_unexpected_ways() + except Exception: + do_something_if_it_failed() + # Bad. + try: + someting_that_may_fail_in_unexpected_ways() + except: + do_something_if_it_failed() + * Use either ``try ... except`` or ``try ... finally``, but do not mix ``except`` with ``finally`` (which is not supported in Python 2.4). You can however embed one into the other to mimic the ``try ... except ... @@ -287,14 +304,14 @@ # Good. try: try: - something_that_may_fail() + something_that_may_fail_with_some_known_error() except SomeError: do_something_if_it_failed() finally: always_do_this_regardless_of_what_happened() # Bad. try: - something_that_may_fail() + something_that_may_fail_with_some_known_error() except SomeError: do_something_if_it_failed() finally: