Python-20 异常处理 异常检测

方式一:

  try

    检测范围

  except Exception[ as reason]:

    出现异常(Exception)后的处理代码

方式二:try-finally语句

  try:

    检测范围

  except Exception[as reason]:

    出现异常(Exception)后的处理代码

  finally:

    无论如何都会被执行的代码

raise语句

方式一:

try:
    f = open('我为什么是一个文件.txt')
    print(f.read())
    f.close()
except OSError:
    print('文件出错拉T_T')

运行结果:

[fengjunjie@localhost ~]$ python3 test.py
文件出错拉T_T

try:
    f = open('我为什么是一个文件.txt')
    print(f.read())
    f.close()
except OSError as reason:
    print('文件出错拉T_T,错误的原因是:' + str(reason))

 运行结果:

[fengjunjie@localhost ~]$ python3.6 test.py
文件出错拉T_T,错误的原因是:[Errno 2] No such file or directory: '我为什么是一个文件.txt'

try:
    sum = 1 + '1'
    f = open('我为什么是一个文件.txt')
    print(f.read())
    f.close()
except OSError as reason:
    print('文件出错拉T_T,错误的原因是:' + str(reason))
except TypeError:
    print('类型转换错误')

运行结果:

[fengjunjie@localhost ~]$ python3 test.py
类型转换错误

try:
    int('abc')
    sum = 1 + '1'
    f = open('我为什么是一个文件.txt')
    print(f.read())
    f.close()
except OSError as reason:
    print('文件出错拉T_T,错误的原因是:' + str(reason))
except TypeError as reason:
    print('类型转换错误,错误原因' + str(reason))
except:
    print('程序出错了')

运行结果:

[fengjunjie@localhost ~]$ python3 test.py
程序出错了

同时捕获多个异常:

try:
    sum = 1 + '1'
    f = open('我为什么是一个文件.txt')
    print(f.read())
    f.close()
except (OSError,TypeError):
    print('程序出错了')

运行结果:

[fengjunjie@localhost ~]$ python3 test.py
程序出错了

方式二:

finally -- 文件关闭

try:
    f = open('我为什么是一个文件.txt','w')
    print(f.write('我存在了!'))
    sum = 1 + '1'
except (OSError,TypeError):
    print('程序出错了')
finally:
    f.close()

运行结果:

[fengjunjie@localhost ~]$ python3 test.py
5
程序出错了

raise

>>> raise
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: No active exception to reraise

>>> raise ZeroDivisionError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError
>>> raise ZeroDivisionError('除书为零的异常')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: 除书为零的异常

posted @ 2017-09-11 14:27  110528844  阅读(336)  评论(0编辑  收藏  举报