Python:异常处理

# 异常处理
# 方式一
try:
    pass
except Exception as f:
    pass

# 方式二
try:
    pass
except Exception as e:
    pass  # try中代码异常,则此代码执行
finally:
    pass  # 无论是否出现异常,此代码都会执行,一般用于释放资源,如果try有return,则finally下面的代码会先执行再return

num1 = input("请输入第一个数值:")
num2 = input('请输入第二个数值:')
try:
    result = int(num1) * int(num2)
    print(result)
except Exception as e:
    print('输入错误')
finally:
    print('Goodjob!!!')

# 异常细分
try:
    pass
# except XXX as e:
#     pass
except Exception as e:  # 可以捕获所有错误
    pass

# 自定义异常
# 案例
import re


class EmailErro(Exception):
    title = '邮箱格式错误!'


class PhoneErro(Exception):
    title = '手机格式错误!'


def sendmessage():
    email_num = input("请输入邮箱:")
    phone_num = input("请输入手机:")
    if not re.match('\w+@\w+.com', email_num):
        raise EmailErro
    if not re.findall('\d+', phone_num):
        raise PhoneErro
    print('我的邮箱是{},手机号码是{}!'.format(email_num, phone_num))


def excute():
    try:
        sendmessage()
    except EmailErro as e:
        pass
    except PhoneErro as e:
        pass
    except Exception as e:
        print('发送失败')


excute()
上一篇:ES安装步骤


下一篇:Kubernetes-ConfigMap