如何在 Python 中使用 Exception 捕獲 ValueError?


當函式接收型別正確但值無效的值時,會使用 ValueError。

可以如下重寫給定的程式碼以處理異常並找到它的型別。

示例

import sys
try:
n = int('magnolia')
except Exception as e:
print e
print sys.exc_type

輸出

invalid literal for int() with base 10: 'magnolia'
<type 'exceptions.ValueError'>

更新日期:2020-6-12

298 次瀏覽

開啟你的事業

完成課程獲得認證

開始
廣告