''' python異常類的繼承關係 BaseException是全部異常類的父親,除了系統退出,按鍵錯誤等,其餘都是Exception的子類,類的繼承關係以下所示 BaseException -- SystemExit -- KeyboardInterrupt -- GeneratorExit +- Exception -- StopIteration +- StandardError -- BufferError +- ArithmeticError -- FloatingPointError -- OverflowError -- ZeroDivisionError -- AssertionError -- AttributeError +- EnvironmentError -- IOError +- OSError -- WindowsError (Windows) -- VMSError (VMS) -- EOFError -- ImportError +- LookupError -- IndexError -- KeyError -- MemoryError +- NameError -- UnboundLocalError -- ReferenceError +- RuntimeError -- NotImplementedError +- SyntaxError +- IndentationError -- TabError -- SystemError -- TypeError +- ValueError +- UnicodeError -- UnicodeDecodeError -- UnicodeEncodeError -- UnicodeTranslateError +- Warning -- DeprecationWarning -- PendingDeprecationWarning -- RuntimeWarning -- SyntaxWarning -- UserWarning -- FutureWarning -- ImportWarning -- UnicodeWarning -- BytesWarning ''' ''' 捕獲異常 ''' try: a = 1 b = 2 print(a+b) except ValueError: #只捕獲異常,不對異常信息輸出 print('input number error') except IOError as error: #捕獲異常並輸出異常信息 print('io error',error) except (IndexError,KeyError) as error: #捕獲多個異常(以元組形式添加) print('io error', error) except Exception as error: #捕獲全部繼承自Exception的異常 print(error) raise AttributeError #拋出異常 except: #捕獲全部異常 print('error') else: #未發生異常,必須在except以後 print('not eror') finally: #不管會不會出現異常,都會執行 print('next input') ''' 自定義異常類 ''' class AddException(Exception): #直接繼承 pass class InsetException(Exception): key_code = 'code' key_message = 'message' def __init__(self,**kwargs): self.code = kwargs[InsetException.key_code] self.message = kwargs[InsetException.key_message] def __str__(self): print('code:{},message:{}'.format(self.code,self.message)) ''' 引用自定義異常類 ''' raise InsetException(code=15,message='inset error')