python异常处理

python yekong

错误

文件未找到报错


print('test')
f = open('text.txt', 'r')
print('text2')

try捕获异常

不报错


try:
    print('test')
    f = open('text.txt', 'r')
    print('text2')
except IOError:
    pass


try:
    print('test')
    f = open('text.txt', 'r')
    print('text2')
except IOError:
    print('文件不存在')

捕获不同类型的错误异常


try:
    print('test')
    f = open('text.txt', 'r')
    print('text2')
except (IOError, NameError) as result:
    print('文件不存在')
    print(result)

捕获所有异常


try:
    print('test')
    f = open('text.txt', 'r')
    print('text2')
except Exception as result:
    print('文件不存在')
    print(result)

不管有没有异常一定要执行finally


try:
    print('test')
    f = open('text.txt', 'r')
    print('text2')
except Exception as result:
    print('文件不存在')
    print(result)
finally:
    print('text2')

喜欢