2024.5.23

8-4 【Python0017】设计异常处理类Cexception,并基于异常处理类设计并实现日期类Date
分数 10
作者 doublebest
单位 石家庄铁道大学

【题目描述】定义一个异常类Cexception解决日期类实现中的自定义异常处理。设计的日期类应包含以下内容:

① 有三个成员数据:年、月、日;

② 有设置日期的成员函数;

③ 有用格式"月/日/年"输出日期的成员函数;

④ 要求在日期设置及有参构造函数中添加异常处理。

程序中定义各种日期对象并测试。
【注意事项】闰年的 2 月的天数为 29天,其它年份 2 月28 天;闰年是指:年份能被 4且不能被 100 整除,或者年份能被 400 整除。

注意日期间的关联。
【练习要求】请给出源代码程序和运行测试结果,源代码程序要求添加必要的注释。

# 定义自定义异常类

class Cexception(Exception):

def __init__(self, message):

super().__init__(message)

# 定义日期类

class Date:

def __init__(self, year, month, day):

# 在构造函数中进行日期有效性检查

self.set_date(year, month, day)

# 判断是否是闰年

def is_leap_year(self, year):

return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

# 设置日期并处理异常

def set_date(self, year, month, day):

# 判断月份的范围

if not (1 <= month <= 12):

raise Cexception("Invalid month. It should be between 1 and 12.")

# 根据月份判断日期的范围

if month == 2:

if self.is_leap_year(year):

max_days = 29

else:

max_days = 28

elif month in [4, 6, 9, 11]:

max_days = 30

else:

max_days = 31

if not (1 <= day <= max_days):

raise Cexception(f"Invalid day. For month {month}, it should be between 1 and {max_days}.")

self.year = year

self.month = month

self.day = day

# 返回格式化的日期

def __str__(self):

return f"{self.month}/{self.day}/{self.year}"

# 测试

if __name__ == "__main__":

try:

# 创建日期对象并测试

date1 = Date(2023, 10, 31) # 合法日期

print(date1)

date2 = Date(2024, 2, 29) # 闰年合法日期

print(date2)

date3 = Date(2023, 2, 29) # 非闰年非法日期

except Cexception as ex:

print("Exception:", ex)

try:

date4 = Date(2023, 13, 1) # 非法月份

except Cexception as ex:

print("Exception:", ex)

try:

date5 = Date(2023, 10, 32) # 超出最大天数

except Cexception as ex:

print("Exception:", ex)

 

posted @   liuxuechao  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示