Python錯誤處理機(jī)制

@(python程序員)[Python]


Python Cookbook

捕獲所有的異常

處理異常的時候最好還會盡可能地使用精確的異常類贮折。

def parse_int(s):
    try:
        n = int(v)
    except Exception as e:
        print("Couldn't parse")
        print("Reason:",e)

parse_int('42')
#Couldn't parse
#Reason: name 'v' is not defined

Learning Python

Exception Basics

Suppose we write the following function:

def fetcher(obj, index):
    return obj[index]

x = 'spam'
fetcher(x, 3)
#'m'

Catching Exceptions

def catcher():
    try:
        fetcher(x, 4)
    except IndexError:
        print('got exception')
    print('continuing')

catcher()
#got exception
#continuing

Raising Exceptions

try:
    raise IndexError # Trigger exception manually
except IndexError:
    print('got exception')

Exception Coding Details

  • try/except
    Catch and recover from exceptions raised by Python, or by you.
  • try/finally
    Perform cleanup actions, whether exceptions occur or not.
  • raise
    Trigger an exception manually in your code.
  • assert
    Conditionally trigger an exception in your code.
  • with/as
    Implement context managers in Python 2.6, 3.0, and later (optional in 2.5).

The try/except/else Statement

try:
    statements # Run this main action first
except name1:
    statements # Run if name1 is raised during try block
except (name2, name3):
    statements # Run if any of these exceptions occur
except name4 as var:
    statements # Run if name4 is raised, assign instance raised to var
except:
    statements # Run for all other exceptions raised
else:
    statements # Run if no exception was raised during try block

with/as Context Managers

The basic format of the with statement looks like this

with expression [as variable]:
    with-block

Pro Python Best Practices

Exceptions in Python

The Error Type

Technically, an error message means that Python has raised an Exception. The error type indicates which Exception class was raised. All Exceptions are subclasses of the Exception class. In Python 3.5, there is a total of 47 different Exception types. You can see the full list of Exceptions with

所有的Exceptions都是Exception類的子類参歹。在Python3.5中一共有47中Exception類型绵咱。

[x for x in dir(__builtins__) if 'Error' in x]
Figure: Hierarchy of Python Exceptions

Catching Exceptions

For sure, the following usage of try.. except is a terrible idea:

try:
    call_some_functions()
except:
    pass

This construct is known as the diaper pattern. It catches everything, but after a while you don’t want to look inside. It makes the Exception disappear, but creates a worse problem instead: the Exceptions are covered, but so are our possibilities do diagnose what is going on. A Best Practice is to use try.. except only for well-defined situations instead, and to always catch a specific Exception type.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末兜蠕,一起剝皮案震驚了整個濱河市兜粘,隨后出現(xiàn)的幾起案子构挤,更是在濱河造成了極大的恐慌散吵,老刑警劉巖耽装,帶你破解...
    沈念sama閱讀 206,968評論 6 482
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件愤炸,死亡現(xiàn)場離奇詭異,居然都是意外死亡掉奄,警方通過查閱死者的電腦和手機(jī)规个,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,601評論 2 382
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來姓建,“玉大人诞仓,你說我怎么就攤上這事∷偻茫” “怎么了墅拭?”我有些...
    開封第一講書人閱讀 153,220評論 0 344
  • 文/不壞的土叔 我叫張陵,是天一觀的道長涣狗。 經(jīng)常有香客問我谍婉,道長舒憾,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,416評論 1 279
  • 正文 為了忘掉前任穗熬,我火速辦了婚禮镀迂,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘唤蔗。我一直安慰自己招拙,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,425評論 5 374
  • 文/花漫 我一把揭開白布措译。 她就那樣靜靜地躺著别凤,像睡著了一般。 火紅的嫁衣襯著肌膚如雪领虹。 梳的紋絲不亂的頭發(fā)上规哪,一...
    開封第一講書人閱讀 49,144評論 1 285
  • 那天,我揣著相機(jī)與錄音塌衰,去河邊找鬼诉稍。 笑死,一個胖子當(dāng)著我的面吹牛最疆,可吹牛的內(nèi)容都是我干的杯巨。 我是一名探鬼主播,決...
    沈念sama閱讀 38,432評論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼努酸,長吁一口氣:“原來是場噩夢啊……” “哼服爷!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起获诈,我...
    開封第一講書人閱讀 37,088評論 0 261
  • 序言:老撾萬榮一對情侶失蹤仍源,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后舔涎,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體笼踩,經(jīng)...
    沈念sama閱讀 43,586評論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,028評論 2 325
  • 正文 我和宋清朗相戀三年亡嫌,在試婚紗的時候發(fā)現(xiàn)自己被綠了嚎于。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,137評論 1 334
  • 序言:一個原本活蹦亂跳的男人離奇死亡挟冠,死狀恐怖于购,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情圃郊,我是刑警寧澤价涝,帶...
    沈念sama閱讀 33,783評論 4 324
  • 正文 年R本政府宣布,位于F島的核電站持舆,受9級特大地震影響色瘩,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜逸寓,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,343評論 3 307
  • 文/蒙蒙 一居兆、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧竹伸,春花似錦泥栖、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,333評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至譬嚣,卻和暖如春钢颂,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背拜银。 一陣腳步聲響...
    開封第一講書人閱讀 31,559評論 1 262
  • 我被黑心中介騙來泰國打工殊鞭, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留茶鹃,地道東北人孙乖。 一個月前我還...
    沈念sama閱讀 45,595評論 2 355
  • 正文 我出身青樓塘匣,卻偏偏與公主長得像好爬,于是被迫代替她去往敵國和親流译。 傳聞我的和親對象是個殘疾皇子司草,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,901評論 2 345

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