10.31Python 异常

try:
    file = open("test.txt")    #会报错的东西
except FileNotFoundError as error:
    print("error:", error)    #不报错

很喜欢小蓝的一句话:怎么报错!!怎么不报错!!

try:
    num_one = int(input("输入被除数:"))
    num_two = int(input("输入除数:"))
    print("结果:", num_one / num_two)
except (ValueError, ZeroDivisionError) as error:    #输入数为0,输入数为空
    print("error:", error)

抛异常

try:
    raise IndexError("123")
except:
    raise

限定上传文件格式

class OError(EOFError):
    def __init__(self, suffix):
        self.suffix = suffix


picture = input("请上传图片:")
for i in range(len(picture)):
    if picture[i] == ".":
        suffix = picture[i + 1:]
try:
    if suffix != "jpg" and suffix != "png" and suffix != "jpeg":
        raise OError(suffix)
except OError as error:
    print("error:图片格式不能是", error)
else:
    print("上传成功")