【问题标题】:Catching ZeroDivisionError捕捉 ZeroDivisionError
【发布时间】:2019-10-07 17:55:01
【问题描述】:

在我的异常处理中,我试图捕捉 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()

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

【问题讨论】:

  • 你能分享你得到的输出吗?实际上你做了except Exception as err。这就是为什么
  • 至少,except ZeroDivisionError 应该高于except Exception as err,因为ZeroDivisionError 派生自Exception。换句话说,在其当前状态下,ZeroDivisionError 块将永远不会被命中,因为除以零将在 Exception 块中处理。
  • @0x5453 我刚刚将 except ZeroDivisionError 切换到最后一个 except ,但仍然没有运气。
  • 我刚刚输入了一系列用于测试异常错误的数字。我已经尝试了所有的零,几个零。每次它拉回 0.0 作为平均值而不是给我一个 ZeroDivisionError
  • 我推荐阅读How to debug small programs。这应该很容易通过调试器或简单地通过添加一些 print 语句来解决。

标签: python exception divide-by-zero


【解决方案1】:

您需要更改捕获异常的顺序。由于 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.')

【讨论】:

  • 我把它改成了这个,但还是没有运气。它仍然给我 0.0 作为我的输出,而不是拉出错误。
  • 是否有另一个异常被异常处理捕获?
  • 没有。它以 0.0 的形式返回,而不是捕获异常。
  • 我认为您的程序中某处还有另一个逻辑问题。尝试运行而不捕获任何异常。我还将围绕异常应该捕获的代码进行异常处理。例如,在打开文件的代码周围放置 IOError 处理程序,在除法周围放置 DivisionByZero 处理程序等。
猜你喜欢
  • 2017-07-15
  • 1970-01-01
  • 2021-07-10
  • 2012-04-27
  • 1970-01-01
  • 1970-01-01
  • 2020-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多