当前位置:   article > 正文

python中try怎么用_Python中try语句的用法

python try

1. try except语句的用法,用来检测一段代码内出现的异常并将其归类输出相关信息,首先是try: 被检测代码段  except Exception[as reason]: 相关信息,举例说明:

>>> try:

f = open('该文档不存在')

print(f.read())

f.close()

except OSError:

print('文件出错了T_T')

文件出错了T_T

当然,我们也可以在except Exception 加上 as reason将程序检测到的出错的信息输出,举例说明:

try:

f = open('该文档不存在')

print(f.read())

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('该文档不存在')

print(f.read())

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('该文档不存在')

print(f.read())

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 fishc

NameError: name 'fishc' is not defined

另外,可以将Exception信息放在一个except语句下面,举例说明:

try:

fishc

1 + '1'

f = open('该文档不存在')

print(f.read())

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('该文档不存在')

print(f.read())

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')

print(f.read())

f.close()

出错了T_T

出错原因是name 'fishc' is not defined

我爱鱼C论坛!

3. raise语句,raise Exception,引入一个异常,举例说明:

>>> raise NameError

Traceback (most recent call last):

File "", line 1, in raise NameError

NameError

>>> raise ZeroDivisionError('除数是0')

Traceback (most recent call last):

File "", line 1, in raise ZeroDivisionError('除数是0')

ZeroDivisionError: 除数是0

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/414659?site
推荐阅读
相关标签
  

闽ICP备14008679号