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

后端 未结 10 2120
情深已故
情深已故 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"
       ....:
    

提交回复
热议问题