Python中的内置异常你知道那些,欢迎留言评论~~~

Python中的所有实例必须是从BaseException派生的类的实例。通过子类不相关的两个异常类,即使它们具有相同的名称,也永远不会等效。内置异常可以由解释器或内置函数生成。

错误发生时,Python中会引发一些内置的异常。可以使用local()内置函数来查看这些内置异常,如下所示:

>>> locals()['__ builtins__']

这将返回内置异常,函数和属性的字典。

基类

以下异常通常用作其他异常的基类。

 1、exception BaseException
这是所有内置异常的基类。它并不意味着被用户定义的类直接继承。对于用户定义的类,使用Exception。此类负责使用传递的参数使用str()创建异常的字符串表示形式。如果没有参数,则返回一个空字符串。

  • args: args是提供给异常构造函数的参数的元组。

  • with_traceback(tb):此方法通常用于异常处理中。此方法将tb设置为该异常的新回溯并返回异常对象。

    代码:

try:
    ...
except SomeException:
    tb = sys.exc_info()[2]
    raise OtherException(...).with_traceback(tb)

 2、exception Exception
这是所有内置的非系统退出异常的基类。所有用户定义的异常也应从此类派生。

3、exception ArithmeticError
此类是针对各种算术错误(例如:)引发的那些内置异常的基类:

    • OverflowError

    • ZeroDivisionError

    • FloatingPointError

    范例:

    try:   
        a = 10/0  
        print a   
    except ArithmeticError:   
            print "此语句引发算术异常."  
    else:   
        print "Success."
    

    输出:

    此语句引发算术异常。
    

    4、exception BufferError
    当无法执行与缓冲区相关的操作时,将引发此异常。

    5、exception LookupError
    这是在映射或序列上使用的键或索引无效或找不到时引发的那些异常的基类。引发的异常是:

      • KeyError

      • IndexError

      范例:

      try:  
          a = [1, 2, 3]  
          print a[3]  
      except LookupError:  
          print "索引越界错误."
      else:  
          print "Success"
      

      输出:

      索引越界错误.
      

      具体例外

      以下异常是通常引发的异常。

      异常AssertionError
      当断言语句失败时,引发AssertionError。

      范例:

      assert False,“断言失败”
      输出:
      Traceback (most recent call last):
        File "exceptions_AssertionError.py", line 12, in 
          assert False, 'The assertion failed'
      AssertionError: The assertion failed
      

      exception AttributeError
      当属性引用或分配失败(例如,引用了不存在的属性)时,将引发AttributeError。

      范例:

      class Attributes(object): 
          pass
        
      object = Attributes() 
      print object.attribute
      

      输出:

      Traceback (most recent call last):
        File "d912bae549a2b42953bc62da114ae7a7.py", line 5, in 
          print object.attribute
      AttributeError: 'Attributes' object has no attribute 'attribute'
      

      exception EOFError
      当类似input()的内置函数遇到文件结尾条件(EOF)而没有读取任何数据时,引发 EOFError。诸如readline()之类的文件方法在到达EOF时会返回一个空字符串。

      范例:

      while True: 
          data = raw_input('输入名称: ') 
          print 'Hello  ', data
      
      
      

      输出:

      输入名称:Hello 软件测试test 
      输入名称:Traceback(最近一次通话):
        文件“ exceptions_EOFError.py”,第13行,
          数据= raw_input('输入名称:')
      EOFError:读取行时出现EOF
      

      异常FloatingPointError
      当浮点操作失败时,引发FloatingPointError。总是定义此异常,但是只有在使用–with-fpectl选项配置Python或在pyconfig.h文件中定义了WANT_SIGFPE_HANDLER符号时,才会引发此异常。

      范例:

      import math 
        
      print math.exp(1000)
      

      输出:

      Traceback (most recent call last):
        File "", line 1, in 
      FloatingPointError: in math_1
      

      异常GeneratorExit
      该异常直接继承自BaseException,而不是Exception,因为从技术上讲,它不是错误。关闭生成器或协程时,将引发GeneratorExit异常。

      范例:

      def my_generator(): 
          try: 
              for i in range(5): 
                  print 'Yielding', i 
                  yield i 
          except GeneratorExit: 
              print 'Exiting early'
        
      g = my_generator() 
      print g.next() 
      g.close()
      

      输出:

      Yielding 0
      0
      Exiting early
      

      异常ImportError
      当import语句无法加载模块或from…import中的“ from list”具有无法找到的名称时,引发ImportError。

      • 范例:

      import module_does_not_exist
      
      输出:
      Traceback (most recent call last):
        File "exceptions_ImportError_nomodule.py", line 12, in 
          import module_does_not_exist
      ImportError: No module named module_does_not_exist
      
      • 范例:

      from exceptions import Userexception 
      
      • 输出:

      Traceback (most recent call last):
        File "exceptions_ImportError_missingname.py", line 12, in 
          from exceptions import Userexception
      ImportError: cannot import name Userexception
      

      exception ModuleNotFoundError
      这是ImportError的子类,当找不到模块时,import会引发该子类。在sys.modules中找不到None时,也会引发此错误。

      exception IndexError
      当引用的序列超出范围时,引发IndexError。

      范例:

      array = [ 0, 1, 2 ] 
      print array[3]
      

      输出:

      Traceback (most recent call last):
        File "exceptions_IndexError.py", line 13, in 
          print array[3]
      IndexError: list index out of range
      

      exception KeyError
      当在一组现有键中找不到映射键时,引发KeyError。

      范例:

      array = { 'a':1, 'b':2 } 
      print array['c']
      

      输出:

      Traceback (most recent call last):
        File "exceptions_KeyError.py", line 13, in 
          print array['c']
      KeyError: 'c'
      

      exception KeyboardInterrupt
      当用户按下中断键(例如Control-C或Delete)时,将引发此错误。

      范例:

      try: 
          print '按Return或Ctrl-C:', 
          ignored = raw_input() 
      except Exception, err: 
          print '捕获到异常:', err 
      except KeyboardInterrupt, err: 
          print '捕捉到键盘中断'
      else: 
          print '没有错误'
      

      输出:

      按Return键或Ctrl-C键:^ 捕捉到键盘中断
      

      exception MemoryError
      当操作内存不足时,将引发此错误。

      范例:

      def fact(a): 
          factors = [] 
          for i in range(1, a+1): 
              if a%i == 0: 
                  factors.append(i) 
          return factors  
        
      num = 600851475143
      print fact(num)
      

      输出:

      Traceback (most recent call last):
        File "4af5c316c749aff128df20714536b8f3.py", line 9, in 
          print fact(num)
        File "4af5c316c749aff128df20714536b8f3.py", line 3, in fact
          for i in range(1, a+1):
      MemoryError
      

      异常NameError
      如果找不到本地或全局名称,则会引发此错误。例如,不合格的变量名。

      范例:

      def func(): 
          print ans 
        
      func() 
      

      输出:

      Traceback (most recent call last):
        File "cfba0a5196b05397e0a23b1b5b8c7e19.py", line 4, in 
          func()
        File "cfba0a5196b05397e0a23b1b5b8c7e19.py", line 2, in func
          print ans
      NameError: global name 'ans' is not defined
      

      异常NotImplementedError
      此异常派生自RuntimeError。当派生类覆盖该方法时,用户定义的类中的抽象方法应引发此异常。

      范例:

      class BaseClass(object): 
          """定义接口"""
          def __init__(self): 
              super(BaseClass, self).__init__() 
          def do_something(self): 
              """接口,未实现"""
              raise NotImplementedError(self.__class__.__name__ + '.do_something') 
        
      class SubClass(BaseClass): 
          """实现接口"""
          def do_something(self): 
              """真的做了些什么"""
              print self.__class__.__name__ + ' doing something!'
        
      SubClass().do_something() 
      BaseClass().do_something()
      

      输出:

      Traceback (most recent call last):
        File "b32fc445850cbc23cd2f081ba1c1d60b.py", line 16, in 
          BaseClass().do_something()
        File "b32fc445850cbc23cd2f081ba1c1d60b.py", line 7, in do_something
          raise NotImplementedError(self.__class__.__name__ + '.do_something')
      NotImplementedError: BaseClass.do_something
      

      异常OSError([arg])
      当系统函数返回与系统相关的错误,包括I / O故障(例如“找不到文件”或“磁盘已满”错误)时,将引发OSError异常。

      范例:

      Traceback (most recent call last):
        File "442eccd7535a2704adbe372cb731fc0f.py", line 4, in 
          print i, os.ttyname(i)
      OSError: [Errno 25] Inappropriate ioctl for device
      

      exception OverflowError
      当算术运算的结果超出范围时,将引发OverflowError。整数引发MemoryError而不是OverflowError。对于超出所需范围的整数,有时会引发OverflowError。由于缺乏C语言中浮点异常处理的标准化,因此未检查浮点操作。

      范例:

      import sys 
        
      print '正则整数: (maxint=%s)' % sys.maxint 
      try: 
          i = sys.maxint * 3
          print '没有溢出 ', type(i), 'i =', i 
      except OverflowError, err: 
          print '溢出于 ', i, err 
        
      print
      print '长整数:'
      for i in range(0, 100, 10): 
          print '%2d' % i, 2L ** i 
        
      print
      print '浮点值:'
      try: 
          f = 2.0**i 
          for i in range(100): 
              print i, f 
              f = f ** 2
      except OverflowError, err: 
          print '之后溢出 ', f, err
      

      输出:

      定期整数:(MAXINT = 9223372036854775807)
      没有溢出,对于i = 27670116110564327421 
      
      
      长整数:
       0 1 
      10 1024 
      20 1048576 
      30 1073741824 
      40 1099511627776 
      50 1125899906842624 
      60 1152921504606846976 
      70个1180591620717411303424 
      80 1208925819614629174706176 
      90 1237940039285380274899124224 
      
      
      浮点值:
      0 1.23794003929e + 27 
      1 + 1.53249554087e 54 
      2 2.34854258277e + 108 
      3 5.5156522631e + 216 
      在5.5156522631e + 216之后溢出(34,'数值结果超出范围')
      

      异常RecursionError
      RecursionError源自RuntimeError。当解释器检测到超过最大递归深度时,将引发此异常。

      异常ReferenceError
      当在垃圾回收之后使用弱引用代理访问引用对象的属性时,引发ReferenceError。

      范例:

      import gc 
      import weakref 
        
      class Foo(object): 
        
          def __init__(self, name): 
              self.name = name 
            
          def __del__(self): 
              print '(Deleting %s)' % self
        
      obj = Foo('obj') 
      p = weakref.proxy(obj) 
        
      print '之前:', p.name 
      obj = None
      print '之后:', p.name 
      

      输出:

      BEFORE: obj
      (Deleting )
      AFTER:
      
      
      Traceback (most recent call last):
        File "49d0c29d8fe607b862c02f4e1cb6c756.py", line 17, in 
          print 'AFTER:', p.name
      ReferenceError: weakly-referenced object no longer exists
      

      exception RuntimeError
      当没有其他异常适用时,将引发RuntimeError。它返回一个字符串,指示确切的错误。

      异常StopIteration
      内置函数next()和迭代器的__next __()方法引发StopIteration错误,以表示所有项目都是由迭代器产生的。

      范例:

      Arr = [3, 1, 2] 
      i=iter(Arr) 
        
      print i 
      print i.next() 
      print i.next() 
      print i.next() 
      print i.next()
      

      输出:

      3
      1
      2
      
      
      Traceback (most recent call last):
        File "2136fa9a620e14f8436bb60d5395cc5b.py", line 8, in 
          print i.next()
      StopIteration
      

      异常SyntaxError
      当解析器遇到语法错误时,引发SyntaxError。在import语句中或在调用内置函数exec()或eval()时,或在读取初始脚本或标准输入时,可能会发生语法错误。

      范例:

      try: 
          print eval('软件测试test') 
      except SyntaxError, err: 
          print 'Syntax error %s (%s-%s): %s' % \ 
              (err.filename, err.lineno, err.offset, err.text) 
          print err 
      

      输出:

      Syntax error  (1-9): 软件测试test
      invalid syntax (, line 1)
      

      异常SystemError
      当解释器发现内部错误时,将引发SystemError。关联的值是一个字符串,指出出了什么问题。

      exception SystemExit
      调用sys.exit()函数时,将引发SystemExit。调用sys.exit()会转换为异常,以执行清理处理程序(try语句的最终子句)并调试脚本,而不会冒失去控制权的风险。

      异常TypeError
      当将操作或函数应用于不适当类型的对象时,引发 TypeError。此异常返回一个字符串,其中提供有关类型不匹配的详细信息。

      范例:

      arr = ('tuple', ) + 'string'
      print arr
      

      输出:

      Traceback (most recent call last):
        File "30238c120c0868eba7e13a06c0b1b1e4.py", line 1, in 
          arr = ('tuple', ) + 'string'
      TypeError: can only concatenate tuple (not "str") to tuple
      

      exception UnboundLocalError
      UnboundLocalError是NameError的子类,当在函数或方法中对局部变量进行引用但未为该变量赋值时会引发该异常

      范例:

      
      
      def global_name_error(): 
          print 未知的全局名
        
      def unbound_local(): 
          local_val = local_val + 1
          print 本地名称
        
      try: 
          global_name_error() 
      except NameError, err: 
          print '全局名称错误:', err 
        
      try: 
          unbound_local() 
      except UnboundLocalError, err: 
          print '本地名称错误:', err 
      

      输出:

      Global name error: global name '全局名称错误' is not defined
      Local name error: local variable '本地名称' referenced before assignment
      

      异常UnicodeError
      此异常是ValueError的子类。当发生与Unicode相关的编码或解码错误时,会引发UnicodeError。

      异常ValueError
      当内置操作或函数接收到具有正确类型但无效值的参数时,引发ValueError。

      范例:

      print int('a') 
      

      输出:

      Traceback (most recent call last):
        File "44f00efda935715a3c5468d899080381.py", line 1, in 
          print int('a')
      ValueError: invalid literal for int() with base 10: 'a'
      

      exception ZeroDivisionError
      当除法或模运算的第二个参数为零时,将引发ZeroDivisionError。该异常返回一个字符串,指示操作数和操作的类型。

      范例:

      print 1/0
      

      输出:

      Traceback (most recent call last):
        File "c31d9626b41e53d170a78eac7d98cb85.py", line 1, in 
          print 1/0
      ZeroDivisionError: integer division or modulo by zero
      

      使用Python读取,写入和解析JSON

      建立数据驱动,关键字驱动和混合Selenium框架这些你了解吗

      您需要了解的有关Selenium等待方法

      如何在Selenium WebDriver中查找元素?(二)

      如何在Selenium WebDriver中查找元素?(一)

      • 0
        点赞
      • 0
        收藏
        觉得还不错? 一键收藏
      • 打赏
        打赏
      • 0
        评论

      “相关推荐”对你有帮助么?

      • 非常没帮助
      • 没帮助
      • 一般
      • 有帮助
      • 非常有帮助
      提交
      评论
      添加红包

      请填写红包祝福语或标题

      红包个数最小为10个

      红包金额最低5元

      当前余额3.43前往充值 >
      需支付:10.00
      成就一亿技术人!
      领取后你会自动成为博主和红包主的粉丝 规则
      hope_wisdom
      发出的红包

      打赏作者

      软件测试test

      你的鼓励将是我创作的最大动力

      ¥1 ¥2 ¥4 ¥6 ¥10 ¥20
      扫码支付:¥1
      获取中
      扫码支付

      您的余额不足,请更换扫码支付或充值

      打赏作者

      实付
      使用余额支付
      点击重新获取
      扫码支付
      钱包余额 0

      抵扣说明:

      1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
      2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

      余额充值