如何使用自定義訊息實現一個自定義的 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP