99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁(yè)精彩閱讀Python錯(cuò)誤和異常小結(jié)
Python錯(cuò)誤和異常小結(jié)
2017-07-26
收藏

Python錯(cuò)誤和異常小結(jié)

事先說(shuō)明哦,這不是一篇關(guān)于Python異常的全面介紹的文章,這只是在學(xué)習(xí)Python異常后的一篇筆記式的記錄和小結(jié)性質(zhì)的文章。什么?你還不知道什么是異常,額...

1.Python異常類

Python是面向?qū)ο笳Z(yǔ)言,所以程序拋出的異常也是類。常見的Python異常有以下幾個(gè),大家只要大致掃一眼,有個(gè)映像,等到編程的時(shí)候,相信大家肯定會(huì)不只一次跟他們照面(除非你不用Python了)。


2.捕獲異常

Python完整的捕獲異常的語(yǔ)句有點(diǎn)像:

try:
    try_suite
except Exception1,Exception2,...,Argument:
    exception_suite
......   #other exception block
else:
    no_exceptions_detected_suite
finally:
    always_execute_suite

額...是不是很復(fù)雜?當(dāng)然,當(dāng)我們要捕獲異常的時(shí)候,并不是必須要按照上面那種格式完全寫下來(lái),我們可以丟掉else語(yǔ)句,或者finally語(yǔ)句;甚至不要exception語(yǔ)句,而保留finally語(yǔ)句。額,暈了?好吧,下面,我們就來(lái)一一說(shuō)明啦。

2.1.try...except...語(yǔ)句

try_suite不消我說(shuō)大家也知道,是我們需要進(jìn)行捕獲異常的代碼。而except語(yǔ)句是關(guān)鍵,我們try捕獲了代碼段try_suite里的異常后,將交給except來(lái)處理。

try...except語(yǔ)句最簡(jiǎn)單的形式如下:

try:
    try_suite
except:
    exception block

上面except子句不跟任何異常和異常參數(shù),所以無(wú)論try捕獲了任何異常,都將交給except子句的exception block來(lái)處理。如果我們要處理特定的異常,比如說(shuō),我們只想處理除零異常,如果其他異常出現(xiàn),就讓其拋出不做處理,該怎么辦呢?這個(gè)時(shí)候,我們就要給except子句傳入異常參數(shù)啦!那個(gè)ExceptionN就是我們要給except子句的異常類(請(qǐng)參考異常類那個(gè)表格),表示如果捕獲到這類異常,就交給這個(gè)except子句來(lái)處理。比如:

try:
    try_suite
except Exception:
    exception block

舉個(gè)例子:

>>> try:
...     res = 2/0
... except ZeroDivisionError:
...     print "Error:Divisor must not be zero!"
...
Error:Divisor must not be zero!

看,我們真的捕獲到了ZeroDivisionError異常!那如果我想捕獲并處理多個(gè)異常怎么辦呢?有兩種辦法,一種是給一個(gè)except子句傳入多個(gè)異常類參數(shù),另外一種是寫多個(gè)except子句,每個(gè)子句都傳入你想要處理的異常類參數(shù)。甚至,這兩種用法可以混搭呢!下面我就來(lái)舉個(gè)例子。

try:
    floatnum = float(raw_input("Please input a float:"))
    intnum = int(floatnum)
    print 100/intnum
except ZeroDivisionError:
    print "Error:you must input a float num which is large or equal then 1!"
except ValueError:
    print "Error:you must input a float num!"

[root@Cherish tmp]# python test.py
Please input a float:fjia
Error:you must input a float num!
[root@Cherish tmp]# python test.py
Please input a float:0.9999
Error:you must input a float num which is large or equal then 1!
[root@Cherish tmp]# python test.py
Please input a float:25.091
4

上面的例子大家一看都懂,就不再解釋了。只要大家明白,我們的except可以處理一種異常,多種異常,甚至所有異常就可以了。

大家可能注意到了,我們還沒解釋except子句后面那個(gè)Argument是什么東西?別著急,聽我一一道來(lái)。這個(gè)Argument其實(shí)是一個(gè)異常類的實(shí)例(別告訴我你不知到什么是實(shí)例),包含了來(lái)自異常代碼的診斷信息。也就是說(shuō),如果你捕獲了一個(gè)異常,你就可以通過(guò)這個(gè)異常類的實(shí)例來(lái)獲取更多的關(guān)于這個(gè)異常的信息。例如:

>>> try:
...     1/0
... except ZeroDivisionError,reason:
...     pass
...
>>> type(reason)
<type 'exceptions.ZeroDivisionError'>
>>> print reason
integer division or modulo by zero
>>> reason
ZeroDivisionError('integer division or modulo by zero',)
>>> reason.__class__
<type 'exceptions.ZeroDivisionError'>
>>> reason.__class__.__doc__
'Second argument to a division or modulo operation was zero.'
>>> reason.__class__.__name__
'ZeroDivisionError'

上面這個(gè)例子,我們捕獲了除零異常,但是什么都沒做。那個(gè)reason就是異常類ZeroDivisionError的實(shí)例,通過(guò)type就可以看出。

2.2try ... except...else語(yǔ)句
    現(xiàn)在我們來(lái)說(shuō)說(shuō)這個(gè)else語(yǔ)句。Python中有很多特殊的else用法,比如用于條件和循環(huán)。放到try語(yǔ)句中,其作用其實(shí)也差不多:就是當(dāng)沒有檢測(cè)到異常的時(shí)候,則執(zhí)行else語(yǔ)句。舉個(gè)例子大家可能更明白些:

>>> import syslog
>>> try:
...     f = open("/root/test.py")
... except IOError,e:
...     syslog.syslog(syslog.LOG_ERR,"%s"%e)
... else:
...     syslog.syslog(syslog.LOG_INFO,"no exception caught\n")
...
>>> f.close()

2.3 finally子句
    finally子句是無(wú)論是否檢測(cè)到異常,都會(huì)執(zhí)行的一段代碼。我們可以丟掉except子句和else子句,單獨(dú)使用try...finally,也可以配合except等使用。

例如2.2的例子,如果出現(xiàn)其他異常,無(wú)法捕獲,程序異常退出,那么文件 f 就沒有被正常關(guān)閉。這不是我們所希望看到的結(jié)果,但是如果我們把f.close語(yǔ)句放到finally語(yǔ)句中,無(wú)論是否有異常,都會(huì)正常關(guān)閉這個(gè)文件,豈不是很 妙

>>> import syslog
>>> try:
...     f = open("/root/test.py")
... except IOError,e:
...     syslog.syslog(syslog.LOG_ERR,"%s"%e)
... else:
...     syslog.syslog(syslog.LOG_INFO,"no exception caught\n")
... finally:
>>>     f.close()

大家看到了沒,我們上面那個(gè)例子竟然用到了try,except,else,finally這四個(gè)子句!:-),是不是很有趣?到現(xiàn)在,你就基本上已經(jīng)學(xué)會(huì)了如何在Python中捕獲常規(guī)異常并處理之。

3.兩個(gè)特殊的處理異常的簡(jiǎn)便方法

3.1斷言(assert)
    什么是斷言,先看語(yǔ)法:

assert expression[,reason]

其中assert是斷言的關(guān)鍵字。執(zhí)行該語(yǔ)句的時(shí)候,先判斷表達(dá)式expression,如果表達(dá)式為真,則什么都不做;如果表達(dá)式不為真,則拋出異常。reason跟我們之前談到的異常類的實(shí)例一樣。不懂?沒關(guān)系,舉例子!最實(shí)在!

>>> assert len('love') == len('like')
>>> assert 1==1
>>> assert 1==2,"1 is not equal 2!"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: 1 is not equal 2!

我們可以看到,如果assert后面的表達(dá)式為真,則什么都不做,如果不為真,就會(huì)拋出AssertionErro異常,而且我們傳進(jìn)去的字符串會(huì)作為異常類的實(shí)例的具體信息存在。其實(shí),assert異常也可以被try塊捕獲:

>>> try:
...     assert 1 == 2 , "1 is not equal 2!"
... except AssertionError,reason:
...     print "%s:%s"%(reason.__class__.__name__,reason)
...
AssertionError:1 is not equal 2!
>>> type(reason)
<type 'exceptions.AssertionError'>

3.2.上下文管理(with語(yǔ)句)
   如果你使用try,except,finally代碼僅僅是為了保證共享資源(如文件,數(shù)據(jù))的唯一分配,并在任務(wù)結(jié)束后釋放它,那么你就有福了!這個(gè)with語(yǔ)句可以讓你從try,except,finally中解放出來(lái)!語(yǔ)法如下:

with context_expr [as var]:
    with_suite

是不是不明白?很正常,舉個(gè)例子來(lái)!

復(fù)制代碼代碼如下:

>>> with open('/root/test.py') as f:
...     for line in f:
...         print line

上面這幾行代碼干了什么?
    (1)打開文件/root/test.py
    (2)將文件對(duì)象賦值給  f
    (3)將文件所有行輸出
     (4)無(wú)論代碼中是否出現(xiàn)異常,Python都會(huì)為我們關(guān)閉這個(gè)文件,我們不需要關(guān)心這些細(xì)節(jié)。
    這下,是不是明白了,使用with語(yǔ)句來(lái)使用這些共享資源,我們不用擔(dān)心會(huì)因?yàn)槟撤N原因而沒有釋放他。但并不是所有的對(duì)象都可以使用with語(yǔ)句,只有支持上下文管理協(xié)議(context management protocol)的對(duì)象才可以,那哪些對(duì)象支持該協(xié)議呢?如下表:
file

decimal.Context
thread.LockType
threading.Lock
threading.RLock
threading.Condition
threading.Semaphore
threading.BoundedSemaphore

至于什么是上下文管理協(xié)議,如果你不只關(guān)心怎么用with,以及哪些對(duì)象可以使用with,那么我們就不比太關(guān)心這個(gè)問(wèn)題:)

4.拋出異常(raise)

如果我們想要在自己編寫的程序中主動(dòng)拋出異常,該怎么辦呢?raise語(yǔ)句可以幫助我們達(dá)到目的。其基本語(yǔ)法如下:

raise [SomeException [, args [,traceback]]

第一個(gè)參數(shù),SomeException必須是一個(gè)異常類,或異常類的實(shí)例
    第二個(gè)參數(shù)是傳遞給SomeException的參數(shù),必須是一個(gè)元組。這個(gè)參數(shù)用來(lái)傳遞關(guān)于這個(gè)異常的有用信息。
    第三個(gè)參數(shù)traceback很少用,主要是用來(lái)提供一個(gè)跟中記錄對(duì)象(traceback)
    下面我們就來(lái)舉幾個(gè)例子。

>>> raise NameError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError
>>> raise NameError()  #異常類的實(shí)例
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError
>>> raise NameError,("There is a name error","in test.py")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
>>> raise NameError("There is a name error","in test.py")  #注意跟上面一個(gè)例子的區(qū)別
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: ('There is a name error', 'in test.py')
>>> raise NameError,NameError("There is a name error","in test.py")  #注意跟上面一個(gè)例子的區(qū)別
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: ('There is a name error', 'in test.py')

其實(shí),我們最常用的還是,只傳入第一個(gè)參數(shù)用來(lái)指出異常類型,最多再傳入一個(gè)元組,用來(lái)給出說(shuō)明信息。如上面第三個(gè)例子。

5.異常和sys模塊

另一種獲取異常信息的途徑是通過(guò)sys模塊中的exc_info()函數(shù)。該函數(shù)回返回一個(gè)三元組:(異常類,異常類的實(shí)例,跟中記錄對(duì)象)

>>> try:
...     1/0
... except:
...     import sys
...     tuple = sys.exc_info()
...
>>> print tuple
(<type 'exceptions.ZeroDivisionError'>, ZeroDivisionError('integer division or modulo by zero',), <traceback object at 0x7f538a318b48>)
>>> for i in tuple:
...     print i
...
<type 'exceptions.ZeroDivisionError'> #異常類    
integer division or modulo by zero #異常類的實(shí)例
<traceback object at 0x7f538a318b48> #跟蹤記錄對(duì)象



數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼

若不方便掃碼,搜微信號(hào):CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺(tái)檢測(cè)極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說(shuō)明請(qǐng)參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請(qǐng)輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請(qǐng)輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }