2017-03-10 21 views
-2

MITx有兩個例子:6.00.1x。第一個是:如何在python中使用異常(示例)

def fancy_divide(list_of_numbers, index): 
    try: 
     try: 
      raise Exception("0") 
     finally: 
      denom = list_of_numbers[index] 
      for i in range(len(list_of_numbers)): 
       list_of_numbers[i] /= denom 
    except Exception as ex: 
     print(ex) 

當我打電話fancy_divide([0,2,4],0),它顯示了:除零。

第二個例子是:

def fancy_divide(list_of_numbers, index): 
    try: 
     try: 
      denom = list_of_numbers[index] 
      for i in range(len(list_of_numbers)): 
       list_of_numbers[i] /= denom 
     finally: 
      raise Exception("0") 
    except Exception as ex: 
     print(ex) 

當我打電話fancy_divide([0,2,4],0),它顯示:0

爲什麼他們有不同的結果?

+0

沒有什麼來形容。你知道'try'和'finally'是什麼嗎? –

回答

1
def fancy_divide(list_of_numbers, index): 
    ''' As soon as the function is called, interpreter executes the 2nd try block raising Exception('0') 
    Since an exception is raised, finally block would get excuted. 
    Since we passed denom value being zero, Interpreter throws a divide by zero error''' 
    try: 
     try: 
      raise Exception("0") # exception is raised 
     finally: 
      denom = list_of_numbers[index] # finally executed because of exception 
      for i in range(len(list_of_numbers)): 
       list_of_numbers[i] /= denom # Divide by zero Error thrown by interpreter 
    except Exception as ex: 
     print(ex) 

def fancy_divide(list_of_numbers, index): 
    '''You don't require explanation if you understood previous one''' 
    try: 
     try: 
      denom = list_of_numbers[index] 
      for i in range(len(list_of_numbers)): 
       list_of_numbers[i] /= denom # Divide by zero Exception is thrown by interpreter 
     finally: 
      raise Exception("0") # Raises Exception("0") 
    except Exception as ex: 
     print(ex) # prints the same 
+0

爲什麼沒有第一個執行「except Exception ex:」 – jiangniao

+0

@jiangniao它執行了'except Exception as ex:'由於解釋器拋出一個**除零異常,'除了異常如ex'被捕獲並且打印出這個例外。 – vardin

+0

好的,我明白了。謝謝 – jiangniao