Python中try语句的⽤法
1. try except语句的⽤法,⽤来检测⼀段代码内出现的异常并将其归类输出相关信息,⾸先是try: 被检测代码段  except Exception[as reason]: 相关信息,举例说明:
>>> try:
f = open('该⽂档不存在')
ad())
f.close()
except OSError:
print('⽂件出错了T_T')
⽂件出错了T_T
当然,我们也可以在except Exception 加上 as reason将程序检测到的出错的信息输出,举例说明:
try:
f = open('该⽂档不存在')
ad())
f.close()
except OSError as reason:
print('⽂件出错了T_T')
print('出错原因是%s'%str(reason))
⽂件出错了T_T
出错原因是[Errno 2] No such file or directory: '该⽂档不存在'
当然,可以增加多个except语句,提取代码段不同的异常问题,举例说明:
try:
1 + '1'
f = open('该⽂档不存在')
ad())
f.close()
except OSError as reason:
print('⽂件出错了T_T')
print('出错原因是%s'%str(reason))
except TypeError as reason:
print('求和出错了T_T')
print('出错原因是%s'%str(reason))
求和出错了T_T
出错原因是unsupported operand type(s) for +: 'int' and 'str'
但是需要注意程序检测到第⼀个异常后即停⽌运⾏,在except中到相应输出语句,如果except未包含时,则直接曝出异常,
try:
fishc
1 + '1'
f = open('该⽂档不存在')
ad())
f.close()
except OSError as reason:
print('⽂件出错了T_T')
print('出错原因是%s'%str(reason))
except TypeError as reason:
print('求和出错了T_T')
print('出错原因是%s'%str(reason))
Traceback (most recent call last):
File "D:/Python34/test/033/01.py", line 2, in <module>
fishc
NameError: name 'fishc' is not defined
另外,可以将Exception信息放在⼀个except语句下⾯,举例说明:
try:
fishc
1 + '1'
f = open('该⽂档不存在')
ad())
f.close()
except (OSError,TypeError,NameError) as reason:
print('出错了T_T')
print('出错原因是%s'%str(reason))
出错了T_T
出错原因是name 'fishc' is not defined
甚⾄except语句连Except都不要了,则程序检测到异常就会执⾏except下的语句,但不推荐使⽤:try:
fishc
1 + '1'
f = open('该⽂档不存在')
ad())
f.close()
except:
print('出错了T_T')
出错了T_T
2. try finally语句,⼀般是在try except语句下⾯补充,⽤于程序检测到异常后仍能执⾏的语句:
try:
fishc
1 + '1'
f = open('新⽂档.txt',wt)
except (OSError,TypeError,NameError) as reason:
print('出错了T_T')
print('出错原因是%s'%str(reason))
finally:
f = open('新⽂档.txt','wt')
f.write('我爱鱼C论坛!')
f.close()
f = open('新⽂档.txt','rt')python的try和except用法
ad())
f.close()
出错了T_T
出错原因是name 'fishc' is not defined
我爱鱼C论坛!
3. raise语句,raise Exception,引⼊⼀个异常,举例说明:
>>> raise NameError
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
raise NameError
NameError
>>> raise ZeroDivisionError('除数是0')
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
raise ZeroDivisionError('除数是0')
ZeroDivisionError: 除数是0

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。