Python-异常

一、写法

python 复制代码
try:
	可能发生错误的代码
except:
	如果出现异常执行的代码
python 复制代码
try:
	f=open('test.txt','r')
except:
	f=open('test.txt','w')

二、捕获指定异常

python 复制代码
try:
	可能发生错误的代码
except:
	如果捕获到该异常类型执行的代码
python 复制代码
try:
	print(num)
except NameError:
	print('有错误')

1.如果尝试执行的代码异常类型与要捕获的异常类型不一致,则无法捕获异常

2.一般try下方只放一行尝试执行的代码

python 复制代码
try:
	print(1/10)
except(NameError,zeroDivisionError):
	print('有错误')

当捕获多个异常时,可以把要捕获的异常类型名字 放到except后,并使用元组 的方式进行书写

(1)捕获异常描述信息

python 复制代码
try:
	print(num)
except(NameError,zeroDivisionError) as result:
	print(result)

(2)捕获所有的异常
Exception:所有程序异常类的父类

python 复制代码
try:
	print(num)
except Exception as result:
	print(result)

三、异常的小部分

1.异常的else

else表示为如果没有异常要执行的代码

python 复制代码
try:
	print(1)
except Exception as result:
	print(result)
else:
	print('我是else,我是没有异常时要执行的代码')

2.异常的finally

finally表示为无论是否异常均要执行的代码

python 复制代码
try:
	f=open('test.txt','r')
except Exception as result:
	f=open('test.txt','w')
else:
	print('无异常')
finally:
	f.close()

四、异常的传递

python 复制代码
import time
try:
	f=open('test.txt')
	try:
		while True:
			content=f.readline()
			if len(content)==0:
				break
			time.sleep(2)
			print(content)
	except:
		print('意外终止了读取数据')
	finally:
		f.close()
		print('关闭文件')
except:
	print('没有这个文件')

五、自定义异常

python 复制代码
#模拟输密码系统,密码不足3位/错误报异常
class ShortInputError(Exception):
	def _init_(self,length,min_len):
		self.length=length
		self.min_len=min_len
	def _str_(self):
		return f'请输入你要输入的长度为{self.length},不可以少于{self.min_len}个字符'
def main():
	try:
		con=input('请输入密码:')
		if len(con)<3:
			raise ShortInputError(len(con),3)
		except Exception as result:
			print(result)
		else:
			print('密码输入完成')
相关推荐
孟健9 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞11 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽13 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程18 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪18 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook18 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python