首先我們來看一個具有例外拋出功能的程式:
def register(): username=input("please input your user name: ") if len(username)<6: raise Exception("the str must be over 6 places") else: print("the user name you have input is ", username) try: register() except Exception as e: print(e) print("rigister failed") else: print("rigister succeed")#如果沒有執行except,那么直接執行 finally: print("the program is over")
在這一段代碼當中,運用了最為典型的Python例外處理的結構,首先try,然后except,然后else,最后finally,同時我們在程式的最上方定義了一個rigister()函式,將會在下方的try陳述句里進行呼叫,這個函式的意思是:如果說輸入的用戶名稱位數小于6位則報錯,并拋出例外,沒有的話則說明輸入正確,但是既然已經拋出了例外我們為什么還需要用except陳述句呢?
原因是我們拋出例外之后只是系統知道了有這個例外,但是并沒有對它進行處理,因此我們還需要except陳述句對拋出的例外進行接收,然后再進行相應的處理,這就是例外拋出之后還需要使用except陳述句接收的原因!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/162492.html
標籤:Python
