classMyException(Exception):def__init__(self, msg,*args,**kwargs):super().__init__(*args,**kwargs)
self.msg = msg
try:raise MyException('XXX失败了')except MyException as e:print('MyException异常被触发:', e.msg)except Exception as e:print('Exception:', e)
classMyException(Exception):
title ='请求错误'try:raise MyException()except MyException as e:print('MyException异常被触发:', e.title)except Exception as e:print('Exception:', e)
使用场景一
"""定义函数send_email"""classEmailValidError(Exception):
title ='邮箱格式错误'classContentRequiredError(Exception):
title ='文本不能为空错误'defsend_email(email, content):ifnot re.match('\w+@live.com', email):raise EmailValidError()iflen(content)==0:raise ContentRequiredError()# 发送邮件代码...# ...
"""调用方调用以上send_email函数"""defexecute():# 其他代码# ...try:
send_email(...)except EmailValidError as e:passexcept ContentRequiredError as e:passexcept Exception as e:print('发送失败')
execute()
场景二
"""在框架内部已经定义好,遇到不同的错误触发不同的异常"""import requests
from requests import exceptions
whileTrue:
url =input("输入网址:")try:
res = requests.get(url=url)print(res)except exceptions.MissingSchema as e:print('url架构不存在')except exceptions.InvalidSchema as e:print('url架构错误')except exceptions.InvalidURL as e:print('url地址格式错误')except exceptions.ConnectionError as e:print('网络连接错误')except Exception as e:print('代码出现错误', e)