如何在 Python 中捕獲 FloatingPointError 異常?


當浮點異常控制 (fpectl) 開啟時,浮點運算會引發 FloatingPointError,該運算導致了錯誤。啟用 fpectl 需要使用 --with-fpectl 標誌來編譯直譯器。

以下為重寫後的程式碼,它可處理異常並找到其型別。

示例

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

輸出

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

更新於:2020 年 2 月 12 日

1K+ 瀏覽量

開啟你的職業生涯

完成課程獲取認證

立即開始
廣告
© . All rights reserved.