天天看點

python學習第十八天 --錯誤&異常處理

這一章節主要講解python的錯誤和異常處理

什麼是錯誤和異常?及其差別?

錯誤:

1、文法錯誤:代碼不符合解釋器或者編譯器文法。

2、邏輯錯誤:不完整或者不合法輸入或者計算出現問題。

異常:執行過程中出現問題導緻程式無法執行。

1、程式遇到邏輯或者算法問題。

2、運作過程中計算機錯誤(記憶體不夠或者IO錯誤)。

錯誤和異常的差別:

錯誤:代碼運作前的文法或者邏輯錯誤,文法錯誤在執行前修改,邏輯錯誤無法修改。

異常分為兩個步驟:

1、異常産生,檢查到錯誤且解釋器認為是異常,抛出異常。

2、異常處理,截獲異常,忽略或者終止程式處理異常。

常見錯誤:

1:a:NameError

2.if True:SyntaxError

3.f = open('1.txt'):IOError

4.10/0:ZeroDivisionError

5.a =int('dd'):ValueError

try-except用法

try:
try_suite
except Exception[e]:
exception_block
else:
nor - exception      

規則:

1.try用來捕獲try_suite中的錯誤,并且将錯誤交給except處理.

2.except用來處理異常,如果處理異常和設定捕獲異常一緻,使用exception_block處理異常.

3.不能捕獲文法錯誤,如果處理異常和設定捕獲異常不一緻,會将異常抛給python解釋器.

try:
    a = int('dd')
except ValueError,e:
    print 'catch exception: %s'% e

    
catch exception: invalid literal for int() with base 10: 'dd'      

4.try未捕獲的try_suite中的錯誤,輸出else:nor-exception.

try:
    a = int('4')
except ValueError,e:
    print 'catch exception: %s'% e
else:
    print 'nor exception'

nor exception      

5.一旦try捕獲到了錯誤,接下來錯誤後的代碼将不執行,直接執行except.

try:
    a = int('dd')
    print 'success convert to int!'//一旦出現錯誤被捕獲,這句代碼将不執行
except ValueError,e:
    print 'catch exception: %s'% e
else:
    print 'nor exception'

    
catch exception: invalid literal for int() with base 10: 'dd'      

6.處理多個異常時,如果捕獲到異常後,會按順序逐個比對。

try:
    a = int('dd')
    b = 20/0
    print 'success convert to int!'
except ZeroDivisionError,e:
    print 'catch ZeroDivisionError:%s'% e
except ValueError,e:
    print 'catch ValueError: %s'% e
else:
    print 'nor exception'
    
catch ValueError: invalid literal for int() with base 10: 'dd'      

try-finally用法

1、try-finally無論是否檢測到異常,都會執行finally代碼.

2. 作用是為異常處理事件提供清理機制,用來關閉檔案或者釋放資源.

情況一:

try:
try_suite
finally:
do_finally      

1.如果try語句沒有捕獲錯誤,代碼執行do_finally.

2.如果try語句捕獲異常,程式首先執行do_finally.然後将捕獲到的異常抛給python解釋器.

try:
    b = 20/0
finally:
    print 'run to finally'

run to finally

Traceback (most recent call last):
  File "<pyshell#178>", line 2, in <module>
    b = 20/0
ZeroDivisionError: integer division or modulo by zero      
try:
    b = 20/2 //不管是否有錯誤,都會執行finally
finally:
    print 'run to finally'
 
run to finally      

情況二:

try:
try_suite
except:
do_except
finally:
do_finally      

1.若try語句沒有捕獲異常,執行完try代碼段後,執行finally.

2若try捕獲異常,首先執行except處理錯誤,然後執行finally.

try:
    b = 20/0
except ZeroDivisionError,e:
    print 'catch ZeroDivisionError %s'% e
finally:
    print 'run to finally'

catch ZeroDivisionError integer division or modulo by zero
run to finally//即使捕獲到異常後,都會執行finally      

情況三:

try:
try_suite
except:
do_except
else:
do_else
finally:
do_finally      

1.若try語句沒有捕獲異常,執行完try代碼段後,執行else代碼段,最後執行finally。

2、若try捕獲異常,首先執行except處理錯誤,然後執行finally。

try:
    a = '7'
    b = 20/(int(a))
except ValueError,e:
    print 'catch ValueError:%s'% e
else:
    print 'nor exception'
finally:
    print 'run to finally'
    
nor exception
run to finally      

raise 和 assert用法

raise語句用于主動抛出異常.

文法格式:raise[exception[,args]]

exception:異常類  args:描述異常資訊元組 example:raise IOError ‘IO exception’

while True:
    num = int(raw_input('enter 1~100:'))
    if num == 0:
        raise ZeroDivisionError('Value invalid')//主動抛出異常,中斷程式
    else:
        result = 100/num
    
enter 1~100:0

Traceback (most recent call last):
  File "<pyshell#208>", line 4, in <module>
    raise ZeroDivisionError('Value invalid')
ZeroDivisionError: Value invalid       

assert語句用于檢測表達式是否為真,如果為假,引發AsserttionError錯誤。

文法格式:assert expression[,args] expression:表達式  args:判斷條件的描述資訊  example:assert n==1,'n is ont 1'

def bar(s):
    num = int(s)
    assert num!=0,'n is zero!'
    return 10/num

>>> bar('0')

Traceback (most recent call last):
  File "<pyshell#217>", line 1, in <module>
    bar('0')
  File "<pyshell#216>", line 3, in bar
    assert num!=0,'n is zero!'
AssertionError: n is zero      

 啟動Python解釋器時可以用

-O

參數來關閉

assert。

>>>python -o error.py      

關閉後,你可以把所有的

assert

語句當成

pass

來看。