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

后端 未结 10 1994
情深已故
情深已故 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:05

    Python doesn't subscribe to the idea that exceptions should only be used for exceptional cases, in fact the idiom is 'ask for forgiveness, not permission'. This means that using exceptions as a routine part of your flow control is perfectly acceptable, and in fact, encouraged.

    This is generally a good thing, as working this way helps avoid some issues (as an obvious example, race conditions are often avoided), and it tends to make code a little more readable.

    Imagine you have a situation where you take some user input which needs to be processed, but have a default which is already processed. The try: ... except: ... else: ... structure makes for very readable code:

    try:
       raw_value = int(input())
    except ValueError:
       value = some_processed_value
    else: # no error occured
       value = process_value(raw_value)
    

    Compare to how it might work in other languages:

    raw_value = input()
    if valid_number(raw_value):
        value = process_value(int(raw_value))
    else:
        value = some_processed_value
    

    Note the advantages. There is no need to check the value is valid and parse it separately, they are done once. The code also follows a more logical progression, the main code path is first, followed by 'if it doesn't work, do this'.

    The example is naturally a little contrived, but it shows there are cases for this structure.

提交回复
热议问题