Python异常处理

1. Python常见异常
"""
常见异常
	AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
	IOError 输入/输出异常;基本上是无法打开文件
	ImportError 无法引入模块或包;基本上是路径问题或名称错误
	IndentationError 语法错误(的子类) ;代码没有正确对齐
	IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问n x[5]
	KeyError 试图访问字典里不存在的键 inf['xx']
	KeyboardInterrupt Ctrl+C被按下
	NameError 使用一个还未被赋予对象的变量
	SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
	TypeError 传入对象类型与要求的不符合
	UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,导致你以为正在访问它
	ValueError 传入一个调用者不期望的值,即使值的类型是正确的
"""
"""
更多异常:
	ArithmeticError
	AssertionError
	AttributeError
	BaseException
	BufferError
	BytesWarning
	DeprecationWarning
	EnvironmentError
	EOFError
	Exception
	FloatingPointError
	FutureWarning
	GeneratorExit
	ImportError
	ImportWarning
	IndentationError
	IndexError
	IOError
	KeyboardInterrupt
	KeyError
	LookupError
	MemoryError
	NameError
	NotImplementedError
	OSError
	OverflowError
	PendingDeprecationWarning
	ReferenceError
	RuntimeError
	RuntimeWarning
	StandardError
	StopIteration
	SyntaxError
	SyntaxWarning
	SystemError
	SystemExit
	TabError
	TypeError
	UnboundLocalError
	UnicodeDecodeError
	UnicodeEncodeError
	UnicodeError
	UnicodeTranslateError
	UnicodeWarning
	UserWarning
	ValueError
	Warning
	ZeroDivisionError
"""
2. 自定义异常&抛出异常
  • 触发自定义异常,使用raise MyException()实现;示例:
class MyException(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)
class MyException(Exception):
	title = '请求错误'

try:
	raise MyException()
except MyException as e:
	print('MyException异常被触发:', e.title)
except Exception as e:
	print('Exception:', e)
  • 使用场景一
"""定义函数send_email"""
class EmailValidError(Exception):
	title = '邮箱格式错误'

class ContentRequiredError(Exception):
	title = '文本不能为空错误'

def send_email(email, content):
	if not re.match('\w+@live.com', email):
		raise EmailValidError()
		if len(content) == 0:
			raise ContentRequiredError()
		# 发送邮件代码...
	# ...
"""调用方调用以上send_email函数"""
def execute():
	# 其他代码
	# ...
	try:
		send_email(...)
	except EmailValidError as e:
		pass
	except ContentRequiredError as e:
		pass
	except Exception as e:
		print('发送失败')

execute()
  • 场景二
"""在框架内部已经定义好,遇到不同的错误触发不同的异常"""
import requests
from requests import exceptions

while True:
	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)
  • 场景三
"""按照规定触发指定异常,每种异常都具备特殊含义"""
from rest_framework import serializers
from rest_framework.serializers import BaseSerializer, ValidationError


class LoginSmsSerializer(BaseSerializer):
    phone = serializers.CharField(label='手机号', validators=[phone_validator, ])
    code = serializers.CharField(label='短信验证码', validators=[sms_code_validator, ])
    
    def validate(self, attrs):
        """在全局钩子中签发token"""
        
        mobile_phone = attrs.get('phone')
        sms_code = attrs.get('code')
        
        user_object = models.UserInfo.objects.filter(is_active=True, mobile_phone=mobile_phone).first()
        if not user_object:
            raise ValidationError({'phone': '手机号不存在'})
        
        conn = get_redis_connection()
        cache_code = conn.get(mobile_phone)
        if not cache_code:
            raise ValidationError({'code': '验证码不存在或已失效'})
        
        cache_code = cache_code.decode('utf-8')
        if sms_code.strip() != cache_code:
            raise ValidationError({'code': '验证码错误,请重新输入'})
        
        # 验证码使用一次之后,在redis中删除
        conn = get_redis_connection()
        conn.delete(mobile_phone)
        
        extra = model_to_dict(user_object, fields=['real_name', 'token', 'id', 'role'])
        attrs.update(extra)
        return attrs
3. 特殊的finally
  • 在try或excep中即使定义了return,也会执行最后的finally块中的代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值