python,异常处理

# 该例子是对文件异常和类型异常分别进行的处理
try:
    sum = 1+'1'
    f=open('wo.txt')
    print(f.read())
    f.close()
except OSError as reason:
    print('文件出错,错误原因:'+str(reason))
except TypeError as reason:
    print('类型出错,错误原因:'+str(reason))


# 该例子是对文件异常和类型异常同时进行的处理
try:
    sum = 1+'1'
    f=open('wo.txt')
    print(f.read())
    f.close()
except (OSError,TypeError) as reason:
    print('错误:'+str(reason))
    
# 该方法是针对所有类型报错进行处理,但是并不知道报错是什么原因,导致程序员无法处理
try:
    sum = 1+'1'
    f=open('wo.txt')
    print(f.read())
    f.close()
except:
    print('报错了')

# 该方法是针对所有类型报错进行处理,但是并不知道报错是什么原因,导致程序员无法处理
try:
    f=open('wo.txt','w')
    print(f.write('哈哈哈哈'))
    sum = 1+'1'
except:
    print('报错了')
finally:
    f.close()
原文地址:https://www.cnblogs.com/pengpengzhang/p/8686710.html