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

Cách catch FloatingPointError Exception trong Python?

FloatingPointError được raise bởi floating point operations dẫn đến errors, khi floating point exception control (fpectl) được bật. Enabling fpectl yêu cầu interpreter được compile với flag --with-fpectl.

Code cho trước được viết lại như sau để handle exception và tìm type của nó.

Ví dụ

import sys
import math
import fpectl

try:
    print('Control off:', math.exp(700))
    fpectl.turnon_sigfpe()
    print('Control on:', math.exp(1000))
except Exception as e:
    print(e)
    print(sys.exc_type)

Kết quả

Control off: 1.01423205474e+304
Control on: in math_1
<type 'exceptions.FloatingPointError'>