Day10:Python学习笔记(异常处理2)

这篇博客主要介绍了Python的异常处理机制,包括try-except语句的使用,如何通过raise语句主动引发异常,详细的else子句功能,以及try-finally和with语句在自动资源管理中的应用。

异常处理

*try - except 语句 :

try:
	检测范围
except Exception[as reason]:
	出现异常(Exception)后的处理代码*

1.错误提示

f = open('我为什么是一个文件.txt')
print(f.read())
f.close
===================== RESTART: D:/Python/Mypython/test2.py =====================
Traceback (most recent call last):
  File "D:/Python/Mypython/test2.py", line 1, in <module>
    f = open('我为什么是一个文件.txt')
FileNotFoundError: [Errno 2] No such file or directory: '我为什么是一个文件.txt'
>>> 

2.加上try语句,可以执行,提示错误

try:
    f = open('我为什么是一个文件.txt')
    print(f.read())
    f.close
except OSError:
    print('文件出错啦!')
===================== RESTART: D:/Python/Mypython/test2.py =====================
文件出错啦!
>>> 

3.加上reason,提示错误的原因

try:
    f = open('我为什么是一个文件.txt')
    print(f.read())
    f.close
except OSError as reason:
    print('文件出错啦T_T\n错误的原因是:'+str(reason))
===================== RESTART: D:/Python/Mypython/test2.py =====================
文件出错啦T_T
错误的原因是:[Errno 2] No such file or directory: '我为什么是一个文件.txt'
>>> 

4.可以添加多个异常,第一个出现异常输出,停止执行程序

try:
    sum=1+'1'
    f = open('我为什么是一个文件.txt')
    print(f.read())
    f.close
except OSError as reason:
    print('文件出错啦T_T\n错误的原因是:'+str(reason))    
except TypeError as reason:
    print('类型出错啦T_T\n错误的原因是:'+str(reason))
    
===================== RESTART: D:/Python/Mypython/test2.py =====================
类型出错啦T_T
错误的原因是:unsupported operand type(s) for +: 'int' and 'str'
>>> 

5.可以同时处理多个异常

try:
    sum=1+'1'
    f = open('我为什么是一个文件.txt')
    print(f.read())
    f.close
except (OSError,TypeError):   ## 多个异常一起处理
    print('出错啦T_T')
    ===================== RESTART: D:/Python/Mypython/test2.py =====================
出错啦T_T
>>> 

*try - finally 语句 :

try:
	检测范围
except Exception[as reason]:
	出现异常(Exception)后的处理代码*
finally:
	无论如何都会被执行的代码

raise语句(主动引起一个异常)

>>> 1/0
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    1/0
ZeroDivisionError: division by zero
>>> raise ZeroDivisionError
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    raise ZeroDivisionError
ZeroDivisionError
>>> raise ZeroDivisionError('除数为0的异常!')
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    raise ZeroDivisionError('除数为0的异常!')
ZeroDivisionError: 除数为0的异常!
>>> 

丰富的else 语句

1.当执行完while语句时,再执行else。若break了,则不执行else

while 条件:
		执行语句1
		break
 else:
  		执行语句2
def showMaxFactor(num):
    count=num//2     ## 整除,如11//2=5
    while count>1:
        if num%count==0:
            print('%d最大的约数是:%d' %(num,count))
            break    ##若执行到break ,则不执行else
        count-=1     ##若循环内容全部执行完没有路途跳出 ,则执行else
    else:
        print('%d是素数!'%num)

num=int(input('请输入一个整数:'))
showMaxFactor(num)

try --else

try:
    int('abc')    ## 出错,执行异常
except ValueError as reason:
    print('出错啦:'+str(reason))
else:
    print('没有任何异常!')
===================== RESTART: D:\Python\Mypython\新建文本文档.py ====================
出错啦:invalid literal for int() with base 10: 'abc'
>>> >`	
try:
    int('123')      ## 未出错,执行else
except ValueError as reason:
    print('出错啦:'+str(reason))
else:
    print('没有任何异常!')
 ===================== RESTART: D:\Python\Mypython\新建文本文档.py ====================
没有任何异常!
>>> 

with语句(自动调用f.close)

try:
   with open('data.txt','w') as f:
       for each_line in f:
           print(each_line)
except OSError as reason:
    print('出错啦:'+str(reason))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值