ValueError異常是當方法接收正確數據類型但值不合適的參數時,將引發Python中的ValueError異常。 關聯的值是一個字元串,提供有關數據類型不匹配的詳細資訊。用戶代碼可能引發TypeError異常,以指示不支援並且不意圖對某個對象進行嘗試的操作。
ValueError異常及其處理方法:
以ValueError Exception爲例
import math
math.sqrt(-10)
輸出量
Traceback (most recent call last):
File "/Users/krunal/Desktop/code/pyt/database/app.py", line 3, inmath.sqrt(-10) ValueError: math domain error
如您所見,我們收到了ValueError:數學域錯誤。
如何在Python中處理ValueError異常
要處理ValueError異常,請使用try-except塊。
import math
data = 64
try:
print(f"Square Root of {data} is {math.sqrt(data)}")
except ValueError as v:
print(f"You entered {data}, which is not a positive number")
輸出量
Square Root of 64 is 8.0
現在,讓我們將負值分配給數據變量並檢視輸出。
import math
data = -64
try:
print(f"Square Root of {data} is {math.sqrt(data)}")
except ValueError as v:
print(f"You entered {data}, which is not a positive number")
輸出量
You entered -64, which is not a positive number
您可以看到我們的程序引發了ValueError並執行了except塊。
我們的程序可以在int()和math.sqrt()函數中引發ValueError。 因此,我們可以創建一個嵌套的try-except塊來處理它們。