python基础学习1 -异常捕获

#!/usr/bin/env python
# -*- coding:utf-8 -*-

#-------try-except
try:
    file_name = input("请输入需要打开的文件名:")
    f = open(file_name,'r',encoding='utf-8')
    print("文件内容是:")
    for line in f:
        print(line)
except OSError as reason:#文件相关异常包含在内
    print("出现异常,被捕获到了!原因是:"+str(reason))


#多个except语句------
try:
    sum = 1+'1'
except OSError as reason:
    print("错误:%s" % reason)

except TypeError as  reason:
    print("错误:%s" % reason)

try:
    sum = 1+'1'
except (OSError,TypeError) as reason:
    print("错误:%s" % reason)

#---------try-except-finally-----------------------------

try:
    file_name = input("请输入需要打开的文件名:")
    f = open(file_name,'r',encoding='utf-8')
    print("文件内容是:")
    for line in f:
        print(line)
except OSError as reason:#文件相关异常包含在内
    print("出现异常,被捕获到了!原因是:"+str(reason))
finally:
    f.close()
    print("正常关闭了!")
 
#-----------raise 抛出异常-------------
try:
   raise  OSError
except OSError:
    print("出错:")
finally:
    print("close!")

 

posted @ 2016-08-25 11:48  whzym111  阅读(167)  评论(0编辑  收藏  举报