Python基础:内置异常(未完待续)

本文根据Python 3.6.5的官文Built-in Exceptions编写,不会很详细,仅对Python的内置异常进行简单(重难点)介绍——很多异常都可以从名称判断出其意义,罗列所有的内置异常。

在Python中,所有的异常都是派生自BaseException的类的实例。

内置异常可以被继承以定义新的异常类,推荐程序员基于Exception或它的子类去定义新的异常类,而不是基于BaseException,更多自定义异常类的信息请参考User-defined Exceptions

在except或finally从句中产生一个异常时,__context__自动被设置为最后异常捕获;如果新的异常没有被处理,回溯器(traceback,最终被显示出来)会包含最初的和最终的异常。

在产生一个异常时,隐含的异常上下文可以使用和raise一起使用的from来补充明确的原因:

raise new_exc from original_exc

跟随from的表达式必须是一个异常或None,它会被设置在产生的异常的__cause__属性中。(还有更多,翻译不了了)

P.S.上面的信息主要来自官文的翻译,和自己水平有关,并不完整,大家可以参考官文。

1.异常类基类

下面的这些异常类通常用于其它异常类的基类。

exception BaseException

所有异常类的基类,但并不意味着直接被用户定义的类继承(请使用Exception,直接继承又怎样?)

-args

提供给异常类构造器的参数。一些内置异常会期待一定数量的参数,并给这个元组的元素指定一个特殊的意义,而其它的异常类通常被调用时只需要提供一个错误信息的字符串即可。

-with_traceback(tb)

设置tb作为异常的新的回溯器,并返回异常对象。

通常用法如下(引用自官网):

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

exception Exception

 所有内置的、不会导致系统退出的异常类都派生自Exception,所有用户自定义的异常类也应该派生自Exception(第三次提到)。

exception ArithmeticError

 所有算术方面的错误的基类,比如,OverflowError, ZeroDivisionError, FloatingPointError。

exception BufferError

 缓存操作不能被执行时产生此异常。

exception LookupError

在映射对象使用关键字(key)(KeyError)、序列对象使用序号(index)(IndexError) 查找元素时,如果发生错误就会产生此异常的子类。可以直接使用codecs.lookup()产生此异常。

2.具体异常类

 exception AssertionError

exception AttributeError

exception EOFError

exception FloatingPointError

exception GeneratorExit

exception ImportError

exception ModuleNotFoundError

exception IndexError

exception KeyError

exception KeyboardInterrupt

exception MemoryError

exception NameError

exception NotImplementedError

exception OSError([arg])
exception OSError(errno, strerror[, filename[, winerror[, filename2]]])

exception OverflowError

exception RecursionError

exception ReferenceError

exception RuntimeError

exception StopIteration

exception StopAsyncIteration

exception SyntaxError

exception IndentationError

exception TabError

exception SystemError

exception SystemExit

exception TypeError

exception UnboundLocalError

exception UnicodeError

exception UnicodeEncodeError

exception UnicodeDecodeError

exception UnicodeTranslateError

exception ValueError

exception ZeroDivisionError

exception EnvironmentError

exception IOError

exception WindowsError

2.1.OS异常

下面的异常类都是OSError的子类,它们会根据系统错误代码(the system error code,是什么?哪里找?)的值被产生。

exception BlockingIOError

exception ChildProcessError

exception ConnectionError

exception BrokenPipeError

exception ConnectionAbortedError

exception ConnectionRefusedError

exception ConnectionResetError

exception FileExistsError

exception FileNotFoundError

exception InterruptedError

exception IsADirectoryError

exception NotADirectoryError

exception PermissionError

exception ProcessLookupError

exception TimeoutError

3.报警类异常

下面的异常用于报警,更多信息可以查看warnings模块

exception Warning

exception UserWarning

exception DeprecationWarning

exception PendingDeprecationWarning

exception SyntaxWarning

exception RuntimeWarning

exception FutureWarning

exception ImportWarning

exception UnicodeWarning

exception BytesWarning

exception ResourceWarning

4.异常层次结构

来自官文。

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning
原文地址:https://www.cnblogs.com/luo630/p/9176768.html