如何在 Python 中使用異常捕獲 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'>

更新於: 12-Jun-2020

298 次瀏覽

啟動您的 職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.