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 13:59

    This is my simple snippet on howto understand try-except-else-finally block in Python:

    def div(a, b):
        try:
            a/b
        except ZeroDivisionError:
            print("Zero Division Error detected")
        else:
            print("No Zero Division Error")
        finally:
            print("Finally the division of %d/%d is done" % (a, b))
    

    Let's try div 1/1:

    div(1, 1)
    No Zero Division Error
    Finally the division of 1/1 is done
    

    Let's try div 1/0

    div(1, 0)
    Zero Division Error detected
    Finally the division of 1/0 is done
    

提交回复
热议问题