comparison doc/v2_planning/API_coding_style.txt @ 1497:3d4615ee96a4

Added recommendation to use "except Exception:" rather than "except:"
author Olivier Delalleau <delallea@iro>
date Thu, 01 Sep 2011 13:35:02 -0400
parents 7b61bfda1dab
children 2b3cff882382
comparison
equal deleted inserted replaced
1491:8be8cdde97ee 1497:3d4615ee96a4
275 mean_x = sum(x) / float(len(x)) 275 mean_x = sum(x) / float(len(x))
276 # Bad. 276 # Bad.
277 n_samples_per_split = n_samples / n_splits 277 n_samples_per_split = n_samples / n_splits
278 mean_x = sum(x) / len(x) 278 mean_x = sum(x) / len(x)
279 279
280 * If you really have to catch all exceptions, in general you should use
281 ``except Exception:`` rather than ``except:``, as the latter also catches
282 interrupts like when hitting Ctrl-C.
283
284 .. code-block:: python
285
286 # Good (assuming you *must* be catching all exceptions).
287 try:
288 someting_that_may_fail_in_unexpected_ways()
289 except Exception:
290 do_something_if_it_failed()
291 # Bad.
292 try:
293 someting_that_may_fail_in_unexpected_ways()
294 except:
295 do_something_if_it_failed()
296
280 * Use either ``try ... except`` or ``try ... finally``, but do not mix 297 * Use either ``try ... except`` or ``try ... finally``, but do not mix
281 ``except`` with ``finally`` (which is not supported in Python 2.4). 298 ``except`` with ``finally`` (which is not supported in Python 2.4).
282 You can however embed one into the other to mimic the ``try ... except ... 299 You can however embed one into the other to mimic the ``try ... except ...
283 finally`` behavior. 300 finally`` behavior.
284 301
285 .. code-block:: python 302 .. code-block:: python
286 303
287 # Good. 304 # Good.
288 try: 305 try:
289 try: 306 try:
290 something_that_may_fail() 307 something_that_may_fail_with_some_known_error()
291 except SomeError: 308 except SomeError:
292 do_something_if_it_failed() 309 do_something_if_it_failed()
293 finally: 310 finally:
294 always_do_this_regardless_of_what_happened() 311 always_do_this_regardless_of_what_happened()
295 # Bad. 312 # Bad.
296 try: 313 try:
297 something_that_may_fail() 314 something_that_may_fail_with_some_known_error()
298 except SomeError: 315 except SomeError:
299 do_something_if_it_failed() 316 do_something_if_it_failed()
300 finally: 317 finally:
301 always_do_this_regardless_of_what_happened() 318 always_do_this_regardless_of_what_happened()
302 319