首页 > 解决方案 > 捕捉 ZeroDivisionError

问题描述

在我的异常处理中,我试图捕捉 ZeroDivisionError,但由于某种原因,代码仍在进行除以 0 并且没有返回错误。我一定做错了什么,但我似乎无法放置它。

我试图将除法移动到函数中的其他位置,并移动除法错误捕获。

filename = "numbers.txt"

def main():
    total = 0.0
    number = 0.0
    counter = 0
    average = 0


    #Open the numbers.txt file
    try:
        infile = open(filename, 'r')

        #Read the values from the file
        for line in infile:
            counter = counter + 1
            number = float(line)
            total += number

        average = total / counter

        #Close the file
        infile.close()

    except IOError:
        print('An error occurred trying to read the file', end=' ')
        print(filename, '.', sep='')

    except ValueError:
        print('Non-numeric data found in the file', end=' ')
        print(filename, '.', sep='')

    except Exception as err:
        print('A general exception occurred.')
        print(err)

    except ZeroDivisionError:
        print('Cannot devide by zero.')

    else:
        print('Average:', average)
        print('Processing Complete. No errors detected.')




# Call the main function.
main()

我期望结果在除以零时返回错误消息,但它返回零作为答案。

标签: pythonexceptiondivide-by-zero

解决方案


您需要更改捕获异常的顺序。由于 Python 中的所有异常都继承自 Exception 基类,因此您永远不会收到 ZeroDivision 异常,因为它是通过处理 Exception 捕获的。尝试这个:

except IOError:
    print('An error occurred trying to read the file', end=' ')
    print(filename, '.', sep='')

except ValueError:
    print('Non-numeric data found in the file', end=' ')
    print(filename, '.', sep='')

except ZeroDivisionError:
    print('Cannot devide by zero.')

except Exception as err:
    print('A general exception occurred.')
    print(err)

else:
    print('Average:', average)
    print('Processing Complete. No errors detected.')

推荐阅读