异常捕获
异常常规捕获
格式
try:
可能发生错误的代码
except:
如果出现异常执行的代码
捕获指定异常
try:
print(name)
except NameError:
print('name变量名称未定义错误')
多个异常捕获
try:
print(1/0)
except (NameError, ZeroDivisionError):
print('ZeroDivision错误...')
异常捕获并输出描述信息
try:
print(num)
except (NameError, ZeroDivisionError) as e:
print(e)
异常else
try:
print(1)
except Exception as e:
print(e)
else:
print('我是else,是没有异常的时候执行的代码')
异常的finally
try:
f = open('test.txt', 'r')
except Exception as e:
f = open('test.txt', 'w')
else:
print('没有异常,真开心')
finally:
f.close()
实例:
异常的传递
import time
try:
f = open('test.txt')
try:
while True:
content = f.readline()
if len(content) == 0:
break
time.sleep(2)
print(content, end='')
except:
print('意外终止了读取数据')
finally:
f.close()
print('关闭文件')
except:
print("没有这个文件")
抛出自定义异常
class ShortInputError(Exception):
def __init__(self, length, min_length):
self.length = length
self.min_len = min_len
def __str__(self):
return f'您输入的密码长度为{self.length}位,不能少于{self.min_length}个字符'
def main():
try:
password = input('请输入您的密码:')
if len(password) < 6:
raise ShortInputError(len(password), 6)
except Exception as e:
print(e)
else:
print('密码输入完成')
main()
需求:尝试以r
模式打开文件,如果文件不存在,则以w
方式打开
try:
f = open('linux.txt', 'r')
except:
f = open('linux.txt', 'w')
需求:尝试以r
模式打开文件,如果文件不存在,则以w
方式打开
try:
f = open('linux.txt', 'r')
except:
f = open('linux.txt', 'w')