Python——捕获异常

一、什么是异常

"""
异常:错误,bug
处理异常:尝试执行某句可能出现异常的语句,
若出错则用正确的代码去替代。

try:
可能发生错误的代码
except
如果出现异常执行的代码
"""


def t1():
try:
f = open('test.txt', 'r')
except:
f = open('test.txt', 'w')


def t2():
try:
b.bar()
except:
class Car(object):
def bar(self):
print("刹车")


b = Car()
b.bar()


if __name__ == '__main__':
t2()

二、异常类型

(1)"""
1.捕获指定异常,异常类型有多种
2.若尝试执行的代码异常类型与捕获的异常类型不同则报错
3.try下方一般只放一行代码,若有多行可能异常代码,
则捕获一个异常类型后函数返回,及只能捕获一个异常类型。
4.捕获多个指定异常
5.捕获所有异常,Exception 是所有程序异常类的父类
"""

def t3():
"""
捕获多个指定异常
捕获异常描述信息
"""
try:
print(num)
except (NameError, ZeroDivisionError) as result:
print(result)
# name 'num' is not defined


def t4():
try:
print(num)
except Exception as result:
print(result)


if __name__ == '__main__':
# t1()
# t2()
# t3()
t4()

(2)

"""
else:没有异常时执行的代码
finally: 无论是否异常都执行的代码,例如:关闭文件
"""

def t1():
try:
print(1)
except Exception as r:
print(r)
else:
print('我是else,当无异常时执行的代码')


def t2():
try:
f = open('text.txt', 'r')
except Exception as r:
print(r)
f = open('text.txt', 'w')
else:
print('没有异常!')
finally:
print('关闭文件')
f.close()


if __name__ == '__main__':
# t1()
t2()

三、异常传递

"""
异常传递(Exception passing):
异常时可以嵌套书写的,由外到内

案例11.尝试只读打开test.txt 文件,有内容存在则读取,无则提示用户
2.循环读取,无内容时退出循环,若文件意外终止,则提示用户
"""
import time

try:
f = open('text.txt')
try:
while True:
content = f.readline()
if len(content) == 0:
break
time.sleep(2)
print(content)
except:
# 在命令提示符中按 ctrl + c ,进行测试
print('意外终止读取数据')
finally:
f.close()
print('关闭文件')
except:
print('文件不存在')


四、自定义异常

"""
自定义异常(Custom exception
用来报错,不合逻辑的错
案例1:密码长度不足,则报错。
1.自定义异常
2. raise 异常类对象,来抛出异常的描述信息
3.捕获异常
"""


class ShortInputError(Exception):
"""
自定义异常类,继承Exception
"""
def __init__(self, length, min_len):
self.length = length
self.min_len = min_len

def __str__(self):
"""
设置抛出异常的描述信息
"""
return f'您输入的密码长度是{self.length},' \
f'不能小于最小长度 {self.min_len}'


def main1():
try:
code = input('请输入密码:\n')
if len(code) < 3:
# 抛出异常类创建对象
raise ShortInputError(len(code), 3)
except Exception as r:
# 捕获该异常
print(r)
else:
print('密码已输入完成')


if __name__ == '__main__':
main1()

猜你喜欢

转载自www.cnblogs.com/kekefu/p/12346242.html
今日推荐