Is it a good practice to use try-except-else in Python?

后端 未结 10 1983
情深已故
情深已故 2020-11-22 13:50

From time to time in Python, I see the block:

try:
   try_this(whatever)
except SomeException as exception:
   #Handle exception
else:
   return something


        
相关标签:
10条回答
  • 2020-11-22 14:16

    You should be careful about using the finally block, as it is not the same thing as using an else block in the try, except. The finally block will be run regardless of the outcome of the try except.

    In [10]: dict_ = {"a": 1}
    
    In [11]: try:
       ....:     dict_["b"]
       ....: except KeyError:
       ....:     pass
       ....: finally:
       ....:     print "something"
       ....:     
    something
    

    As everyone has noted using the else block causes your code to be more readable, and only runs when an exception is not thrown

    In [14]: try:
                 dict_["b"]
             except KeyError:
                 pass
             else:
                 print "something"
       ....:
    
    0 讨论(0)
  • 2020-11-22 14:18

    "I do not know if it is out of ignorance, but I do not like that kind of programming, as it is using exceptions to perform flow control."

    In the Python world, using exceptions for flow control is common and normal.

    Even the Python core developers use exceptions for flow-control and that style is heavily baked into the language (i.e. the iterator protocol uses StopIteration to signal loop termination).

    In addition, the try-except-style is used to prevent the race-conditions inherent in some of the "look-before-you-leap" constructs. For example, testing os.path.exists results in information that may be out-of-date by the time you use it. Likewise, Queue.full returns information that may be stale. The try-except-else style will produce more reliable code in these cases.

    "It my understanding that exceptions are not errors, they should only be used for exceptional conditions"

    In some other languages, that rule reflects their cultural norms as reflected in their libraries. The "rule" is also based in-part on performance considerations for those languages.

    The Python cultural norm is somewhat different. In many cases, you must use exceptions for control-flow. Also, the use of exceptions in Python does not slow the surrounding code and calling code as it does in some compiled languages (i.e. CPython already implements code for exception checking at every step, regardless of whether you actually use exceptions or not).

    In other words, your understanding that "exceptions are for the exceptional" is a rule that makes sense in some other languages, but not for Python.

    "However, if it is included in the language itself, there must be a good reason for it, isn't it?"

    Besides helping to avoid race-conditions, exceptions are also very useful for pulling error-handling outside loops. This is a necessary optimization in interpreted languages which do not tend to have automatic loop invariant code motion.

    Also, exceptions can simplify code quite a bit in common situations where the ability to handle an issue is far removed from where the issue arose. For example, it is common to have top level user-interface code calling code for business logic which in turn calls low-level routines. Situations arising in the low-level routines (such as duplicate records for unique keys in database accesses) can only be handled in top-level code (such as asking the user for a new key that doesn't conflict with existing keys). The use of exceptions for this kind of control-flow allows the mid-level routines to completely ignore the issue and be nicely decoupled from that aspect of flow-control.

    There is a nice blog post on the indispensibility of exceptions here.

    Also, see this Stack Overflow answer: Are exceptions really for exceptional errors?

    "What is the reason for the try-except-else to exist?"

    The else-clause itself is interesting. It runs when there is no exception but before the finally-clause. That is its primary purpose.

    Without the else-clause, the only option to run additional code before finalization would be the clumsy practice of adding the code to the try-clause. That is clumsy because it risks raising exceptions in code that wasn't intended to be protected by the try-block.

    The use-case of running additional unprotected code prior to finalization doesn't arise very often. So, don't expect to see many examples in published code. It is somewhat rare.

    Another use-case for the else-clause is to perform actions that must occur when no exception occurs and that do not occur when exceptions are handled. For example:

    recip = float('Inf')
    try:
        recip = 1 / f(x)
    except ZeroDivisionError:
        logging.info('Infinite result')
    else:
        logging.info('Finite result')
    

    Another example occurs in unittest runners:

    try:
        tests_run += 1
        run_testcase(case)
    except Exception:
        tests_failed += 1
        logging.exception('Failing test case: %r', case)
        print('F', end='')
    else:
        logging.info('Successful test case: %r', case)
        print('.', end='')
    

    Lastly, the most common use of an else-clause in a try-block is for a bit of beautification (aligning the exceptional outcomes and non-exceptional outcomes at the same level of indentation). This use is always optional and isn't strictly necessary.

    0 讨论(0)
  • 2020-11-22 14:19

    Is it a good practice to use try-except-else in python?

    The answer to this is that it is context dependent. If you do this:

    d = dict()
    try:
        item = d['item']
    except KeyError:
        item = 'default'
    

    It demonstrates that you don't know Python very well. This functionality is encapsulated in the dict.get method:

    item = d.get('item', 'default')
    

    The try/except block is a much more visually cluttered and verbose way of writing what can be efficiently executing in a single line with an atomic method. There are other cases where this is true.

    However, that does not mean that we should avoid all exception handling. In some cases it is preferred to avoid race conditions. Don't check if a file exists, just attempt to open it, and catch the appropriate IOError. For the sake of simplicity and readability, try to encapsulate this or factor it out as apropos.

    Read the Zen of Python, understanding that there are principles that are in tension, and be wary of dogma that relies too heavily on any one of the statements in it.

    0 讨论(0)
  • 2020-11-22 14:26

    See the following example which illustrate everything about try-except-else-finally:

    for i in range(3):
        try:
            y = 1 / i
        except ZeroDivisionError:
            print(f"\ti = {i}")
            print("\tError report: ZeroDivisionError")
        else:
            print(f"\ti = {i}")
            print(f"\tNo error report and y equals {y}")
        finally:
            print("Try block is run.")
    

    Implement it and come by:

        i = 0
        Error report: ZeroDivisionError
    Try block is run.
        i = 1
        No error report and y equals 1.0
    Try block is run.
        i = 2
        No error report and y equals 0.5
    Try block is run.
    
    0 讨论(0)
提交回复
热议问题