如何使用自定义消息实现一个自定义的 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