练习1
def GetAge(age):
try:
if age <= 0:
raise Exception("输入的年龄不符合要求")
except ValueError:
print("年龄必须大于0")
raise
GetAge(-1)
练习2
num_one = int(input("请输入被除数:"))
num_two = int(input("请输入除数:"))
assert num_two != 0, "除数不能为0"
shang = num_one / num_two
print(shang)
练习3
class CustomException(Exception):
def __init__(self, msg):
self.msg = msg
super(CustomException, self).__init__(self.msg)
user_input = input("请输入一个水果名称:")
allow_value = ["apple", "banana"]
def process_user_input(user_input):
print(user_input)
try:
if user_input not in allow_value:
raise CustomException(f"输入的商品不在列表中{user_input}")
process_user_input(user_input)
except CustomException:
print("输入的内容无效")
练习4
class ShortInputError(Exception):
def __init__(self, length, atleast):
self.length = length
self.atleast = atleast
try:
text = input("请输入密码:")
if len(text) < 3:
raise ShortInputError(len(text), 3)
except ShortInputError as result:
print("ShortInputError:输入的长度是%d,长度至少应该是%d" % (result.length, result.atleast))
else:
print('密码设置成功')
© 版权声明
THE END
暂无评论内容