Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách catch OverflowError Exception trong Python?

Khi arithmetic operation vượt quá limits của variable type, OverflowError được raise. Long integers allocate thêm space khi values grow, nên chúng cuối cùng raise MemoryError. Floating point exception handling không standardized. Regular integers được chuyển thành long values khi cần.

Ví dụ

Code cho trước được viết lại để catch exception như sau:

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)

Kết quả

Chúng ta nhận được OverflowError output như sau:

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')