赞
踩
异常目录:了解异常、捕获异常、异常的else、异常的finally、异常的传递、自定义异常
bug ,处理异常是防止程序停止
try:
可能发生错误的代码
except:
如果出现异常执行的代码
例子:以r模式打开文件,如果文件不存在是会报错,防止报错改为w打开
try:
f = open('test.txt','r')
except:
f = open('test.txt','w')
try:
可能发生错误的代码
except 异常类型: #如果异类型不一致,不会执行
如果出现异常且满足异常类型,则执行的代码
例子
try:
print(num)
except NameError:
print('有错误')
捕获多个指定异常
try:
可能发生错误的代码
except (异常类型1,异常类型2):
如果出现异常且满足异常类型,则执行的代码
try:
print(1/0)
except (NameError,ZeroDivisionError):
print('有错误') #正常输出
捕获异常描述信息
try:
可能发生错误的代码
except (异常类型1,异常类型2) as result:
print(result)
try:
print(1/0)
except (NameError,ZeroDivisionError) as result:
print(result) #输出错误信息
捕获所有异常‘
Exception 是所有程序异类的父类
try:
print(1/0)
except Exception as result:
print(result) #输出错误信息
else 没有异常时执行的代码
try:
print(1)
except Exception as result:
print(result) #输出错误信息
else:
print('当没有异常时执行的代码')
finally表示是无论是否异常都要执行的代码,例如关闭文件
try:
f = open('test.txt'.'r')
except Exception as result:
f = open('test.txt'.'W')
finally:
f.close()
在cmd下输入 python3 文件名
也能执行该文件
需求:1,尝试打开test.py文件,如果文件存在则读取文件内容,文件不存在则提示用户即可
2,读取内容要求,尝试循环读取内容,读取过程中如果检测到用户意外终止程序,则except捕获异常,并提示用户。
import time
try:
f = open('test.txt')
try:
while True:
con = f.readline()
if len(con) == 0:
break
time.sleep(2) #让他暂停两秒
print(con)
except:
print('程序被意外终止') #在命名提示符中,如果按下ctrl+c终止键
except:
print('该文件不存在')
异常try是可以嵌套输写
外层的try/except,传到内层的try/except
作用: 用来报错,报不满足程序要求的错
需求:密码长度不足,则报异常(用户输入密码,输入长度不足,则报错,抛出自定义异常,并捕获该异常)
#1,自定义异常类,继承Exception,魔法方法有init和str 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(): #2,抛出异常:尝试执行,用户输入密码,如果长度小于3,抛出异常 try: password = input('请输入密码:') if len(password) <3: #抛出异常类创建的对象 raise ShortInputError(len(password),3) #抛出异常 #3,捕获异常 except Exception as result: print(result) else:#没有异常时捕获的代码 print('没有异常,密码输入正常') main()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。