1. 程式人生 > >python基礎之異常

python基礎之異常

情況一:

>>> try:
	print(num)                #此處產生異常
	print("-----hello-----")  # 上面程式碼產生錯誤,此處不執行,跳過
except NameError:             #  NameError 為異常名稱
	print("-----Error-----")  #try中產生異常,執行此處程式碼

-----Error-----

情況二:

>>> try:
	print(num)                    #此處產生異常
	print("-----hello-----")      #上面程式碼產生錯誤,此處不執行,跳過
except (NameError,FileNotFound):  #NameError 為異常名稱,可以是多個,python3中用元組
	print("-----Error-----")      #try中產生異常,執行此處程式碼

-----Error-----

情況三:

>>> try:
	print(num)                    #此處產生異常
	print("-----hello-----")      #上面程式碼產生錯誤,此處不執行,跳過
except (NameError,FileNotFound):  #NameError 為異常名稱,可以是多個,python3中用元組
	print("-----Error1-----")      #try中產生異常,執行此處程式碼
except Exception:                 #不是上面的異常,其他的異常都會捕捉到
    print("-----Error2-----")

-----Error1-----

情況四:

>>> try:
	print(num)                    #此處產生異常
	print("-----hello-----")      #上面程式碼產生錯誤,此處不執行,跳過
except Exception:                 #無論什麼異常都會捕捉到
    print("-----Error2-----")     #捕捉到異常後,執行下面程式碼

-----Error2-----

情況五:

try:
	print(num)                    #此處產生異常
	print("-----hello-----")      #上面程式碼產生錯誤,此處不執行,跳過
except Exception as ret:          #捕捉到的異常放入ret中,並執行下面的程式碼
    print("-----Error2-----")
    print(ret)

-----Error2-----
name 'num' is not defined

情況六:

try:
	print("-----hello-----")      
except Exception as ret:          #捕捉到的異常放入ret中,並執行下面的程式碼
    print("-----Error2-----")
    print(ret)
else:                             #沒有異常時,執行下面程式碼
	print("-----NoError-----")

-----hello-----
-----NoError-----

情況七:

>>> try:
	print("-----hello-----")      
except Exception as ret:          #捕捉到的異常放入ret中,並執行下面的程式碼
    print("-----Error2-----")
    print(ret)
else:                             #沒有異常時,執行下面程式碼
	print("-----NoError-----")
finally:                          #無論有沒有異常,都執行下面的程式碼
	print("程式執行完畢")

-----hello-----
-----NoError-----
程式執行完畢

異常的傳遞:假如test1()呼叫test2(),test2()中出現異常,但是test2()中沒有對異常的處理,那麼異常將傳遞給test1(),test1()中也沒有異常的處理,那麼異常傳遞給test3(),test3()會處理,不會交給系統。

def test3( ):
    try:
        print("-----3-----")
        test1( )
    except Exception:
        print("-----Error----")