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

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

提交回复
热议问题