如何在 Python 中捕获 OverflowError 异常?

pythonserver side programmingprogramming

当算术运算超出变量类型的限制时,会引发 OverflowError。随着值的增长,长整数会分配更多空间,因此最终会引发 MemoryError。但是,浮点异常处理尚未标准化。常规整数会根据需要转换为长值。

示例

给定的代码被重写为捕获异常,如下所示

i=1
try:
f = 3.0**i
for i in range(100):
print i, f
f = f ** 2
except OverflowError as err:
print 'Overflowed after ', f, err

输出

我们得到以下 OverflowError 作为输出,如下所示

C:/Users/TutorialsPoint1/~scratch_1.py
Floating point values:
0 3.0
1 9.0
2 81.0
3 6561.0
4 43046721.0
5 1.85302018885e+15
6 3.43368382029e+30
7 1.17901845777e+61
8 1.39008452377e+122
9 1.93233498323e+244
Overflowed after 1.93233498323e+244 (34, 'Result too large')


相关文章