Python : Exception

Exception hierarchy?

The class hierarchy for built-in exceptions is:

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
  • exception BaseException?

The base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes (for that, use Exception).

  • exception Exception?

All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class.

for example?

  • 1
>>> MyBad = 'oops'

def stuff( ):
    raise MyBad

>>> try:
        stuff( )
>>> except MyBad:
        print('got it')
...
TypeError: catching classes that do not inherit from BaseException is not allowed

asically, MyBad is not an exception, and the raise statement can only be used with exceptions.
To make MyBad an exception, you must make it extend a subclass of Exception.

  • 2
class MyBad(Exception):
    pass

def stuff( ):
    raise MyBad

>>> try:
        stuff( )
>>> except MyBad:
        print('got it')
...
got it
  • 3
class MyBad(Exception):
    def __init__(self, message):
        super().__init__()
        self.message = message

def stuff(message):
    raise MyBad(message)

>>> try:
        stuff("Your bad")
    except MyBad as error:
        print('got it (message: {})'.format(error.message))
...
got it (message: your bad)

__context__ v.s. __cause__ v.s. __traceback__

This PEP proposes three standard attributes on exception instances: the __context__ attribute for implicitly chained exceptions, the __cause__ attribute for explicitly chained exceptions, and the __traceback__ attribute for the traceback. A new raise ... from statement sets the __cause__ attribute.

  • the name of __cause__ and __context__ ?

For an explicitly chained exception, this PEP suggests __cause__ because of its specific meaning. For an implicitly chained exception, this PEP proposes the name __context__ because the intended meaning is more specific than temporal precedence but less specific than causation: an exception occurs in the context of handling another exception.

  • associated value

Except where mentioned, they have an “associated value” indicating the detailed cause of the error. This may be a string or a tuple of several items of information (e.g., an error code and a string explaining the code). The associated value is usually passed as arguments to the exception class’s constructor.

  • __context__

When raising (or re-raising) an exception in an except or finally clause __context__ is automatically set to the last exception caught; if the new exception is not handled the traceback that is eventually displayed will include the originating exception(s) and the final exception.

>>> try:
...   print(1/0)
... except:
...   raise RuntimeError('Something bad happened')
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: Something bad happened
  • __cause__

When raising a new exception (rather than using a bare raise
to re-raise the exception currently being handled), the implicit exception context can be supplemented with an explicit cause by using from with raise.

raise new_exc from original_exc

The expression following from must be an exception or None. It will be set as __cause__ on the raised exception. Setting __cause__ also implicitly sets the __suppress_context__ attribute to True, so that using
raise new_exc from None
effectively replaces the old exception with the new one for display purposes.

>>> try:
...   print(1/0)
... except Exception as exc:
...   raise RuntimeError('something bad happened') from exc
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: something bad happened

The from clause is used for exception chaining: if given, the second expression must be another exception class or instance, which will then be attached to the raised exception as the __cause__ attribute (which is writable). If the raised exception is not handled, both exceptions will be printed.

  • raise exc from None
>>> try:
...     print(1 / 0)
... except:
...     raise RuntimeError("Something bad happened") from None
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: Something bad happened
  • Exception chaining can be explicitly suppressed by specifying None in the from clause.
  • The default traceback display code shows these chained exceptions in addition to the traceback for the exception itself. An explicitly chained exception in __cause__ is always shown when present. An implicitly chained exception in __context__ is shown only if __cause__ is None and __suppress_context__ is false.
  • In either case, the exception itself is always shown after any chained exceptions so that the final line of the traceback always shows the last exception that was raised.

read more: Built-in Exceptions?

def main(filename):
    file = open(filename)       # oops, forgot the 'w'
        try:
            try:
                compute()
            except Exception, exc:
                log(file, exc)
        finally:
            file.clos()         # oops, misspelled 'close'

def compute():
    1/0

def log(file, exc):
    try:
        print >>file, exc       # oops, file is not writable
    except:
        display(exc)

def display(exc):
    print ex                    # oops, misspelled 'exc'
  • Calling main() with the name of an existing file will trigger four exceptions. The ultimate result will be an AttributeError due to the misspelling of clos, whose __context__ points to a NameError due to the misspelling of ex, whose __context__ points to an IOError due to the file being read-only, whose __context__ points to a ZeroDivisionError, whose __context__ attribute is None.
  • Each thread has an exception context initially set to None.

The __cause__ attribute on exception objects is always initialized to None. It is set by a new form of the raise statement:

raise EXCEPTION from CAUSE

which is equivalent to:

exc = EXCEPTION
exc.__cause__ = CAUSE
raise exc
def print_chain(exc):
    if exc.__cause__:
        print_chain(exc.__cause__)
        print '\nThe above exception was the direct cause...'
    elif exc.__context__:
        print_chain(exc.__context__)
        print '\nDuring handling of the above exception, ...'
    print_exc(exc)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末嫂冻,一起剝皮案震驚了整個(gè)濱河市分蓖,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌裹赴,老刑警劉巖喜庞,帶你破解...
    沈念sama閱讀 206,723評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異棋返,居然都是意外死亡延都,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,485評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門睛竣,熙熙樓的掌柜王于貴愁眉苦臉地迎上來晰房,“玉大人,你說我怎么就攤上這事射沟∈庹撸” “怎么了?”我有些...
    開封第一講書人閱讀 152,998評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵躏惋,是天一觀的道長(zhǎng)幽污。 經(jīng)常有香客問我,道長(zhǎng)簿姨,這世上最難降的妖魔是什么距误? 我笑而不...
    開封第一講書人閱讀 55,323評(píng)論 1 279
  • 正文 為了忘掉前任簸搞,我火速辦了婚禮,結(jié)果婚禮上准潭,老公的妹妹穿的比我還像新娘趁俊。我一直安慰自己,他們只是感情好刑然,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,355評(píng)論 5 374
  • 文/花漫 我一把揭開白布寺擂。 她就那樣靜靜地躺著,像睡著了一般泼掠。 火紅的嫁衣襯著肌膚如雪怔软。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,079評(píng)論 1 285
  • 那天择镇,我揣著相機(jī)與錄音挡逼,去河邊找鬼。 笑死腻豌,一個(gè)胖子當(dāng)著我的面吹牛家坎,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播吝梅,決...
    沈念sama閱讀 38,389評(píng)論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼虱疏,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了苏携?” 一聲冷哼從身側(cè)響起做瞪,我...
    開封第一講書人閱讀 37,019評(píng)論 0 259
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎兜叨,沒想到半個(gè)月后穿扳,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,519評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡国旷,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,971評(píng)論 2 325
  • 正文 我和宋清朗相戀三年矛物,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片跪但。...
    茶點(diǎn)故事閱讀 38,100評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡履羞,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出屡久,到底是詐尸還是另有隱情忆首,我是刑警寧澤,帶...
    沈念sama閱讀 33,738評(píng)論 4 324
  • 正文 年R本政府宣布被环,位于F島的核電站糙及,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏筛欢。R本人自食惡果不足惜浸锨,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,293評(píng)論 3 307
  • 文/蒙蒙 一唇聘、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧柱搜,春花似錦迟郎、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,289評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至健爬,卻和暖如春控乾,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背浑劳。 一陣腳步聲響...
    開封第一講書人閱讀 31,517評(píng)論 1 262
  • 我被黑心中介騙來泰國(guó)打工阱持, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人魔熏。 一個(gè)月前我還...
    沈念sama閱讀 45,547評(píng)論 2 354
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像鸽扁,于是被迫代替她去往敵國(guó)和親蒜绽。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,834評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容