From 3a8a2c5f7b067708f1461d0d31d228c494a88801 Mon Sep 17 00:00:00 2001 From: Rob Browning Date: Sun, 31 Dec 2017 12:29:05 -0600 Subject: [PATCH] CODINGSTYLE: add python exception handling guidelines Signed-off-by: Rob Browning --- CODINGSTYLE | 50 +++++++++++++++++++++++++++++++++++++++++++---- lib/bup/compat.py | 3 +++ 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/CODINGSTYLE b/CODINGSTYLE index 12879e5..1bc76fa 100644 --- a/CODINGSTYLE +++ b/CODINGSTYLE @@ -1,7 +1,14 @@ .. -*-rst-*- -General -======= +C += + +The C implementations should follow the `kernel/git coding style +`_. + + +Python +====== Python code follows `PEP8 `_ with regard to coding style and `PEP257 @@ -23,5 +30,40 @@ blank line in between). Here's an example from Module-level docstrings follow exactly the same guidelines but without the blank line between the summary and the details. -The C implementations should follow the `kernel/git coding style -`_. + +Exception Handling +------------------ + +Avoid finally: blocks in favor of explict catches because a throw +from a finally block will lose any pending exception. An explicit +catch can chain it (see below). + +To behave similarly under Python 2 and 3, use add_ex_tb() to +explicitly add stack traces to any exceptions that are going to be +re-raised by anything other than a no-argument raise (otherwise the +stack trace will be lost):: + + + try: + ... + except ... as ex: + add_ex_tb(ex) + pending_ex = ex + ... + raise pending_ex + +If an exception is thrown from an exception handler, the pending +exception should be "chained" to the new exception as the context. +This can be accomplished via ``chain_ex()``:: + + try: + ... + except ... as ex: + add_ex_tb(ex) + try: + ... + except ... as ex2: + add_ex_tb(ex2) + raise chain_ex(ex2, ex) + +See the end of ``lib/bup/compat.py`` for a functional example. diff --git a/lib/bup/compat.py b/lib/bup/compat.py index 73e89f8..183df9d 100644 --- a/lib/bup/compat.py +++ b/lib/bup/compat.py @@ -3,6 +3,9 @@ from __future__ import print_function from traceback import print_exception import sys +# Please see CODINGSTYLE for important exception handling guidelines +# and the rationale behind add_ex_tb(), chain_ex(), etc. + py_maj = sys.version_info[0] py3 = py_maj >= 3 -- 2.39.2