1.Python内建异常体系结构
The class hierarchy for built-in exceptions is:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StandardError
      |    +-- BufferError
      |    +-- ArithmeticError
      |    |    +-- FloatingPointError
      |    |    +-- OverflowError
      |    |    +-- ZeroDivisionError
      |    +-- AssertionError
      |    +-- AttributeError
      |    +-- EnvironmentError
      |    |    +-- IOError
      |    |    +-- OSError
      |    |         +-- WindowsError (Windows)
      |    |         +-- VMSError (VMS)
      |    +-- EOFError
      |    +-- ImportError
      |    +-- LookupError
      |    |    +-- IndexError
      |    |    +-- KeyError
      |    +-- MemoryError
      |    +-- NameError
      |    |    +-- UnboundLocalError
      |    +-- ReferenceError
      |    +-- RuntimeError
      |    |    +-- NotImplementedError
      |    +-- SyntaxError
      |    |    +-- IndentationError
      |    |         +-- TabError
      |    +-- SystemError
      |    +-- TypeError
      |    +-- ValueError
      |         +-- UnicodeError
      |              +-- UnicodeDecodeError
      |              +-- UnicodeEncodeError
      |              +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
       +-- ImportWarning
       +-- UnicodeWarning
       +-- BytesWarning
2.捕获异常的方式

方法一:捕获所有的异常

''' 捕获异常的第一种方式,捕获所有的异常 '''
    try:
        a = b
        b = c
    except Exception,data:
        print Exception,":",data
    '''输出:<type 'exceptions.Exception'> : local variable 'b' referenced before assignment ''
--------------------------------------------------------------------------------

方法二:采用traceback模块查看异常,需要导入traceback模块

''' 捕获异常的第二种方式,使用traceback查看异常 '''
    try:
        a = b
        b = c
    except:
        print traceback.print_exc()
    '''输出: Traceback (most recent call last):
          File "test.py", line 20, in main
                a = b
        UnboundLocalError: local variable 'b' referenced before assignmen
--------------------------------------------------------------------------------

方法三:采用sys模块回溯最后的异常

''' 捕获异常的第三种方式,使用sys模块捕获异常 '''
    try:
        a = b
        b = c
    except:
        info = sys.exc_info()
        print info
        print info[0]
        print info[1]
    '''输出:
    (<type 'exceptions.UnboundLocalError'>, UnboundLocalError("local variable 'b' referenced before assignment",),
    <traceback object at 0x00D243F0>)
    <type 'exceptions.UnboundLocalError'>
    local variable 'b' referenced before assignment
    '''
-------------------------------------------------------------------------------

1、NameError:尝试访问一个未申明的变量
>>>  v
NameError: name 'v' is not defined

2、ZeroDivisionError:除数为0
>>> v = 1/0
ZeroDivisionError: int division or modulo by zero

3、SyntaxError:语法错误
>>> int int
SyntaxError: invalid syntax (<pyshell#14>, line 1)

4、IndexError:索引超出范围
>>> List = [2]
>>> List[3]
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    List[3]
IndexError: list index out of range

5、KeyError:字典关键字不存在
>>> Dic = {'1':'yes', '2':'no'}
>>> Dic['3']
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    Dic['3']
KeyError: '3'

6、IOError:输入输出错误
>>> f = open('abc')
IOError: [Errno 2] No such file or directory: 'abc'

7、AttributeError:访问未知对象属性
>>> class Worker:
 def Work():
  print("I am working")

>>> w = Worker()
>>> w.a
Traceback (most recent call last):
  File "<pyshell#51>", line 1, in <module>
    w.a
AttributeError: 'Worker' object has no attribute 'a'

8、ValueError:数值错误
>>> int('d')
Traceback (most recent call last):
  File "<pyshell#54>", line 1, in <module>
    int('d')
ValueError: invalid literal for int() with base 10: 'd'

9、TypeError:类型错误
>>> iStr = '22'
>>> iVal = 22
>>> obj = iStr + iVal;
Traceback (most recent call last):
  File "<pyshell#68>", line 1, in <module>
    obj = iStr + iVal;
TypeError: Can't convert 'int' object to str implicitly

10、AssertionError:断言错误
>>> assert 1 != 1
Traceback (most recent call last):
  File "<pyshell#70>", line 1, in <module>
    assert 1 != 1
AssertionError

11、MemoryError:内存耗尽异常

12、NotImplementedError:方法没实现引起的异常

示例:

1 class Base(object):
2 def __init__(self):
3 pass
4
5 def action(self):
6 raise NotImplementedError

定义一个类,一个接口方法action,如果直接调用action则抛NotImplementedError异常,这样做的目的通常是用来模拟接口

13、LookupError:键、值不存在引发的异常

LookupError异常是IndexError、KeyError的基类

如果你不确定数据类型是字典还是列表时,可以用LookupError捕获此异常

14、StandardError 标准异常。

StopIterationGeneratorExitKeyboardInterrupt 和SystemExit外,其他异常都是StandarError的子类。

异常处理有别于错误检测:

错误检测与异常处理区别在于:错误检测是在正常的程序流中,处理不可预见问题的代码,例如一个调用操作未能成功结束

python 异常类型----后期需理解调整的更多相关文章

  1. Python异常类型及包含关系

    Python异常类型及包含关系,设计异常捕获时参考: BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- ...

  2. Python异常类型及处理、自定义异常类型、断言

    异常的概念.识别报错信息 异常处理 断言的基本使用 异常类型(异常就是报错) 常见异常 NameError:名称错误 SyntaxError:语法错误 TypeError:类型错误 错误回溯 查看报错 ...

  3. python 异常类型

    1.NameError:尝试访问一个未申明的变量>>>  vNameError: name 'v' is not defined 2.ZeroDivisionError:除数为0&g ...

  4. 【python】python异常类型

    python2: BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- Stop ...

  5. python异常类型

    python2: BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- Stop ...

  6. python 异常类型大全

    try except 处理异常真舒服!!!

  7. 第二百九十九节,python操作redis缓存-SortSet有序集合类型,可以理解为有序列表

    python操作redis缓存-SortSet有序集合类型,可以理解为有序列表 有序集合,在集合的基础上,为每元素排序:元素的排序需要根据另外一个值来进行比较,所以,对于有序集合,每一个元素有两个值, ...

  8. 第二百九十八节,python操作redis缓存-Set集合类型,可以理解为不能有重复元素的列表

    python操作redis缓存-Set集合类型,可以理解为不能有重复元素的列表 sadd(name,values)name对应的集合中添加元素 #!/usr/bin/env python # -*- ...

  9. 第二百九十七节,python操作redis缓存-List类型,可以理解为列表

    python操作redis缓存-List类型,可以理解为列表,是可以有重复元素的列表 List操作,redis中的List在在内存中按照一个name对应一个List来存储.如图: lpush(name ...

随机推荐

  1. pos提交提交数据时碰到Django csrf

    我的github(PS:希望star):https://github.com/thWinterSun/v-admin 最近在用Vue写前端代码,再用vue-resource向后台提交数据.项目后台是用 ...

  2. code format using astyle

    script context : #! /bin/bash for f in $(find . -name '*.c' -or -name '*.cpp' -or -name '*.h' -type ...

  3. 为何 Delphi的 Local Variables 突然没有值显示了

    可能是上次编译后  code未再修改过. 试试 随便 输入一个空格,然后F9

  4. Windows 7 英文版操作系统中文软件乱码解决方法

    http://blog.csdn.net/lqhbupt/article/details/18863243

  5. Memcached 扩展常用方法

    保存数据 向memcached保存数据的方法有 add replace set 它们的使用方法都相同: $add = $memcached->add( '键', '值', '期限' ); $re ...

  6. 互评Beta版本

    作业要求[https://edu.cnblogs.com/campus/nenu/2018fall/homework/2448] 基于NABCD评论作品,及改进建议 1.杨老师粉丝群.作品:<P ...

  7. python两个子线程通过queue通信

    SocketServer端代码 #!/usr/bin/env python import threading import SocketServer import time import queue ...

  8. 弹出的ViewController半透明效果

    在第一个ViewController做如下设置 let controller = UIStoryboard(name: "Main", bundle: nil).instantia ...

  9. DBWR进程

    --查询dbwr进程号 select pname,spid from v$process where pname like 'DBW%'; PNAME SPID----- -------------- ...

  10. Android manifest 获取源代码

    /********************************************************************************* * Android manifes ...