Python教程

Python:异常处理

本文主要是介绍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()
这篇关于Python:异常处理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!