標籤:類型 -name def 常用 opera 關鍵字 typeerror elf ioerror
一、捕獲異常
1、當程式出錯時,不會展示bug資訊給使用者,而是提供一個友好的提示後,繼續執行程式
2、如下,實現除法,當分母為0時,捕獲並列印出異常資訊;Exception可以捕獲任何異常
def div(x, y): try: print(x/y) except Exception as e: print(‘異常為‘, e)
>>> div(1,0)
異常為 division by zero
也可以指定異常為ZeroDivisionError
def div(x, y): try: print(x/y) except ZeroDivisionError as e: print(‘異常為‘, e)
>>> div(1,0)
異常為 division by zero
3、同時捕獲多個異常
def fdiv(x,y): try: return x/y except TypeError as e: print(‘TypeError: ‘, e) except ZeroDivisionError as e: print(‘ZeroDivisionError: ‘, e) except Exception as e: print(‘其他異常:‘, e)
>>> fdiv(‘ABC‘, 0)
TypeError: unsupported operand type(s) for /: ‘str‘ and ‘int‘
>>> fdiv(12,0)
ZeroDivisionError: division by zero
也可以用以下方式:
def fdiv1(x,y): try: return x/y except (TypeError, ZeroDivisionError, Exception) as e: print(e)
>>> fdiv1(‘ABC‘, 0)
unsupported operand type(s) for /: ‘str‘ and ‘int‘
>>> fdiv1(12,0)
division by zero
二、常用異常
‘---------------IOError:開啟檔案路徑出錯或不存在------------------‘try: f = open(‘error.txt‘,‘r‘)except IOError as e: print(‘開啟檔案出錯, 錯誤資訊:‘, e)‘--------------ImportError:匯入模組路徑出錯或不存在--------------‘try: import errorexcept ImportError as e: print(‘匯入模組出錯, 錯誤資訊:‘, e)‘--------------IndexError:索引出界----------------------------‘list1 = [1,2,3,4,5,6]try: print(list1[6])except IndexError as e: print(‘查詢列表出錯, 錯誤資訊:‘, e)‘----------------keyError:尋找字典中不存在的關鍵字---------------‘dict1 = {1:‘A‘, 2:‘B‘}try: print(dict1[3])except KeyError as e: print(‘查詢字典出錯, 錯誤資訊:‘, e)‘----------------TypeError:參數類型不符----------------------‘def fint(a): print(a/2)try: str1 = ‘ABC‘ fint(str1)except TypeError as e: print(‘參數類型出錯, 錯誤資訊:‘, e)‘------------ValueError:參數類型匹配,但是傳入的值不對------------‘str1 = ‘ABC‘try: print(int(str1))except ValueError as e: print(‘參數值出錯, 錯誤資訊:‘, e)‘------------------NameError:使用的變數沒有賦值------------------‘try: print(a)except NameError as e: print(‘參數出錯, 錯誤資訊:‘, e)
三、自訂異常
class MyException(Exception): def __init__(self, msg): self.message = msg def __str__(self): return self.messagetry: raise MyException(‘自訂異常‘)except MyException as e: print(e)
四、主動拋出異常
try: raise IOError(‘讀寫檔案出錯了‘) #主動拋出IOError異常except IOError as e: print(e)
五、try - except - else - finally
try: f = open(‘test.txt‘, ‘r‘)except IOError as e: #開啟檔案失敗,則拋出異常 print(e)else: #開啟檔案成功,則執行else塊 print(‘執行else‘) f.close()finally: #無論檔案是否正常開啟,都會執行finally塊 print(‘執行finally‘)
Python-異常處理