如何使用自定義訊息實現自定義 Python 異常?


對於上面給出的程式碼,解決方案如下

示例

class CustomValueError(ValueError):
def __init__(self, arg):
self.arg = arg
try:
a = int(input("Enter a number:"))
if not 1 < a < 10:
raise CustomValueError("Value must be within 1 and 10.")
except CustomValueError as e:
print("CustomValueError Exception!", e.arg)

輸出

Enter a number:45
CustomValueError Exception! Value must be within 1 and 10.
Process finished with exit code 0

更新時間:13-Feb-2020

221 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.