如何在python中使用异常(示例)

时间:2017-03-10 03:05:02

标签: 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)):
                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

为什么他们会有不同的结果?

1 个答案:

答案 0 :(得分: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