抛出异常写法: raise KeyError(obj) # obj可以为字符串,数字,元祖,列表,字典等任意类型。
''' 异常处理格式 ''' try: pass except KeyError as e: print("key error..", e) except IndexError as e: print("列表错误", e) except Exception as e: print("未知错误,用在除上面两种情况外的所有错误", e) else: print("一切正常(没有任何错误的时候执行这个)") finally: print("不管出不出错,都会执行这个") ###### try: pass except (KeyError,IndexError) as e: print("两种错误,同一种处理方式") ##### try: pass except Exception as e: print("抓所有错误,一般不在最开始使用") #### ''' 自定义异常 ''' class MyException(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return "自己定义的异常" try: raise MyException("我自定义的异常") except MyException as e: print(e) ''' 输出结果: 一切正常(没有任何错误的时候执行这个) 不管出不出错,都会执行这个 自己定义的异常 '''
==异常树===
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
| +-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning