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

时间:2025-01-20 08:27:26

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

>>> try:

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

print(())

()

except OSError:

print('文件出错了T_T')

文件出错了T_T

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

try:

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

print(())

()

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

()

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

()

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/", line 2, in fishc

NameError: name 'fishc' is not defined

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

try:

fishc

1 + '1'

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

print(())

()

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

()

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

('我爱鱼C论坛!')

()

f = open('新文档.txt','rt')

print(())

()

出错了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