python之异常处理

1.什么是异常?
异常是Python对象,表示一个错误。

2.为什么要做异常的处理?
程序发生异常时,会终止执行(异常发生后面的代码不执行了),为了解决这个问题,需要做异常的处理。

3.异常的分类? (万能的Exception基类)
在这里插入图片描述在这里插入图片描述
4.异常处理的方法
捕捉异常和处理异常:使用try...except...语句
把需要监控的代码放到try语句块下面,把要处理的的方式放到except语句块下面

4.1未做异常处理的报错(1.报错不是很友好;2.报错后的代码不执行了)

f = open('file.txt','r+')
f.write('hello world!')
print("程序报错后,测试是否运行~~~")

Traceback (most recent call last):
  File "E:/chenxian_project/cx/study_cx/study_cx.py", line 2, in <module>
    f = open('file.txt','r+')
FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'

4.2.做了异常处理的报错(1.根据设置的报错信息提示;2.报错后,继续执行后面的代码)

try:
    f = open('file.txt','r+')
    f.write('hello world!')
except IOError as e:
    print('Error:没有找到文件')
print("程序报错后,测试是否运行~~~")

Error:没有找到文件
程序报错后,测试是否运行~~~

5.try…except…else…的用法: try语句块没有发生错误,才执行else下面的代码

try:
    for i in range(10):
        int(i)
except IndexError as e:
    print(e)
else:
    print('***********')

***********

6.try…except…finally…的用法: 不管try语句块有没有发生错误,都要执行finally下面的代码

def dealwith_file():
    try:
        f = open('file.txt',encoding='utf-8')
        for line in f:
            int(line)
        return True
    except Exception as e:
        print(e)
        return False
    finally:
        '''不管try语句中的代码是否报错,都会执行finally分支中的代码'''
        '''去完成一些连接操作的收尾工作'''
        print('finally 被执行了')
        f.close()

r = dealwith_file()
print(r)

finally 被执行了
True

7.使用raise抛出异常(为什么需要把异常抛出来呢?)

try:
    f = open('file1.txt','r+')
    f.write('hello world!')
except IOError as e:
    print('Error:没有找到文件')

    print("程序报错后,测试是否运行~~~")
    raise e

Error:没有找到文件
程序报错后,测试是否运行~~~
Traceback (most recent call last):
  File "E:/chenxian_project/cx/study_cx/study_cx.py", line 15, in <module>
    raise e
  File "E:/chenxian_project/cx/study_cx/study_cx.py", line 9, in <module>
    f = open('file1.txt','r+')
FileNotFoundError: [Errno 2] No such file or directory: 'file1.txt
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值