设为首页 加入收藏

TOP

Python3 异常检测(二)
2018-10-21 18:08:33 】 浏览:174
Tags:Python3 异常 检测
    +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

3、异常处理

1.try语句

try:

  检测范围

except Exception [as reason]:

  出现Exception后处理的代码

 

可以有多个except与try组合,因为检测范围中肯能会产生多个异常,可以用多个except与try组合来关注感兴趣的异常

可以同一处理多类异常 except后要用()把多个需要同一处理的异常括起来

try:
    int('abc')
    sum = 1+'1' 
    f = open('我是一个不存在的文档.txt')
    print(f.read())
    f.close()
except (OSError, ValueError,TypeError)as reason:
    print('出错啦T_T\n错误原因是:' + str(reason))

2.try finally语句

try:

  检测范围

except Exception [as reason]:

  出现Exception后处理的代码

finally:

  一定要做的事情(比如出错后可以在这里把文件关闭)

try:
    f = open('My_File.txt') # 当前文件夹中并不存在"My_File.txt"这个文件T_T
    print(f.read())
except OSError as reason:
    print('出错啦:' + str(reason))
finally:
    if 'f' in locals(): # 如果文件对象变量存在当前局部变量符号表的话,说明打开成功
        f.close()

3、raise语句(引发一个异常)

raise 异常名字

try:
    for i in range(3):
        for j in range(3):
            if i == 2:
                raise KeyboardInterrupt
            print(i, j)
except KeyboardInterrupt:
    print('退出啦!')

 

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Linux进程间通信 --- 管道 下一篇【OJ】 : 容斥原理计算出 1< =..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目