异常处理

异常处理

def div_apple(apple_count):
    """
        分苹果
    """
    person_count = int(input("请输入人数:"))# ValueError
    result = apple_count / person_count# ZeroDivisionError
    print("每个人分到了%d个苹果"%result)

"""
try:
    div_apple(10)
except:
    # 错误的处理逻辑
    print("出错喽")
"""

"""
try:
    div_apple(10)
except ValueError:
    print("输入的人数必须是整数")
except ZeroDivisionError:
    print("输入的人数不能是零")
except Exception:
    # 错误的处理逻辑
    print("出错喽")
else:
    print("没有错误执行的代码")
"""

try:
    # 如果有错误
    div_apple(10)
finally:
    # 不处理错误,但有一件非常重要的事情,必须执行.
    print("一定执行的代码")


print("后续逻辑.........")

抛出异常(信息),接受异常(信息)(as e)

class Wife:
    def __init__(self, age=0):
        self.age = age

    @property
    def age(self):
        return self.__age

    @age.setter
    def age(self,value):
        if 20 <=value <= 30:
            self.__age = value
        else:
            # 抛出/发送  错误信息(异常对象)
            raise ValueError("我不要")

# 接收错误信息
try:
    w01 = Wife(85)
    print(w01.age)
except ValueError as e:
    print(e.args)# 信息

 自定义异常类

class AgeError(Exception):
    def __init__(self, message="", code="", id=0):
        # 消息/错误代码/错误编号....
        self.message = message
        self.code = code
        self.id = id

class Wife:
    def __init__(self, age=0):
        self.age = age

    @property
    def age(self):
        return self.__age

    @age.setter
    def age(self, value):
        if 20 <= value <= 30:
            self.__age = value
        else:
            # 抛出/发送  错误信息(异常对象)
            raise AgeError("我不要", "if 20 <=value <= 30", 101)
            # 需要传递的信息:消息/错误代码/错误编号....

# 接收错误信息
try:
    w01 = Wife(25)
    print(w01.age)
except AgeError as e:
    print(e.id)  # 信息
    print(e.message)  # 信息
    print(e.code)  # 信息
原文地址:https://www.cnblogs.com/NeverYa/p/11223765.html