''' 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')