2024/5/12

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

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

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

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

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

程序中定义各种日期对象并测试。
class CException(Exception):
    def __init__(self, message):
        self.message = message

class Date:
    def __init__(self, year=2000, month=1, day=1):
        try:
            if month < 1 or month > 12:
                raise CException("月份应在1-12之间")
            if day < 1 or day > 31:
                raise CException("日期应在1-31之间")
            if month == 2:
                if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
                    max_days = 29
                else:
                    max_days = 28
            elif month in [4, 6, 9, 11]:
                max_days = 30
            else:
                max_days = 31
            if day > max_days:
                raise CException("日期超出该月最大天数")
        except CException as e:
            print(f"日期设置错误: {e.message}")
            self.year = 2000
            self.month = 1
            self.day = 1
        else:
            self.year = year
            self.month = month
            self.day = day

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

    def display_date(self):
        print(f"日期已设置为:{self.month}/{self.day}/{self.year}")


# 测试日期类
print("日期设置为:2024/2/30")
date1 = Date(2024, 2, 30)  # 日期设置错误,2月没有30号
date1.display_date()  # 输出默认日期 1/1/2000
print( )

print("日期设置为:2024/5/17")
date2 = Date(2024,4, 15)  # 正确的日期设置
date2.display_date()  # 输出日期 5/17/2024
print( )

print("使用默认日期")
date3 = Date()  # 使用默认日期
date3.display_date()  # 输出默认日期 1/1/2000
print( )

print("日期设置为:2024/6/31")
date4 = Date(2024, 6, 31)  # 日期设置错误,6月只有30天
date4.display_date()  # 输出默认日期 1/1/2000

 

posted @ 2024-06-16 21:51  The-rich  阅读(22)  评论(0)    收藏  举报