如何在python中使用异常(示例)
MITx中有两个示例:6.00.1x。第一个是:如何在python中使用异常(示例),python,Python,MITx中有两个示例:6.00.1x。第一个是: 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)): li
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
为什么会有不同的结果
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)
没有什么可以描述的。你知道什么是
try
和finally
了吗?为什么第一个没有执行“Exception as ex:@jiangniao它执行Exception as ex:
因为解释器抛出了一个除零异常,Exception as 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