python基礎之錯誤和異常處理
import Exception # except 在捕獲錯誤異常的時候 是要根據具體的錯誤類型來捕獲的 # 用一個塊 可以捕獲多個不同類型的異常 # EXception 可以捕獲所有異常 當對出現的問題或者錯誤不確定的情況下 可以使用此種 print(dir(Exception)) try: # print(b) #捕獲邏輯的代碼 li=[1,2,3,4] print(li[10]) pass except NameError as msg: # 捕獲到的錯誤 才會在這裡執行 print(msg) pass except IndexError as msg: print(msg) print('初次接觸異常') print('HAHAHAHAHHAHAHAH')
try: # print(b) #捕獲邏輯的代碼 # li=[1,2,3,4] # print(li[10]) a=10/0 pass except NameError as msg: # 捕獲到的錯誤 才會在這裡執行 print(msg) pass except IndexError as msg: print(msg) pass except ZeroDivisionError as msg: print(msg) print('初次接觸異常') print('HAHAHAHAHHAHAHAH')
異常類型
try: print(b) #捕獲邏輯的代碼 # li=[1,2,3,4] # print(li[10]) # a=10/0 pass # except NameError as msg: # # 捕獲到的錯誤 才會在這裡執行 # print(msg) # pass # except IndexError as msg: # print(msg) # pass # except ZeroDivisionError as msg: # print(msg) # pass except Exception as msg: print(msg) pass print('初次接觸異常') print('HAHAHAHAHHAHAHAH')
def A(s): return 10/int(s) pass def B(s): return A(s)*2 def main(): try: B('0') pass except Exception as msg: print(msg) pass pass main() # 不需要在每個可能出錯的地方去捕獲,隻要在合適的層次去捕獲錯誤就可以瞭 這樣的話 就大大減少我們寫try----exception的麻煩 # 異常的拋出機制 #如果在運行時發生異常 解釋器會查找相應的異常捕獲類型 #如果在當前函數裡面沒有找到的話 它會將異常傳遞給上層的調用函數 #如果在最外層 沒有找到的話 解釋器就會退出 程序down掉
class ToolongmyException(Exception): #自定義異常 def __init__(self,leng): ''' :param leng:長度 ''' self.len=leng pass def __str__(self): return '您輸入的數據長度是'+str(self.len)+'已經超過長度瞭' pass def name_Test(): name=input('請輸入姓名:') if len(name)>5: raise ToolongmyException(len(name)) #拋出異常 else: print(name) pass pass name_Test()
class ToolongmyException(Exception): #自定義異常 def __init__(self,leng): ''' :param leng:長度 ''' self.len=leng pass def __str__(self): return '您輸入的數據長度是'+str(self.len)+'已經超過長度瞭' pass def name_Test(): name=input('請輸入姓名:') try: if len(name)>5: raise ToolongmyException(len(name)) #拋出異常 else: print(name) pass except ToolongmyException as result: print(result) pass finally: print('執行完畢瞭') pass name_Test()
總結
本篇文章就到這裡瞭,希望能夠給你帶來幫助,也希望您能夠多多關註WalkonNet的更多內容!