Python中提供了很多异常类用来抛出异常情况,在演示python异常之前,首先要区别异常和错误是两码事。错误主要是指两种错误:1.语法错误;2.逻辑错误,以上2种错误没办法通过固定语法进行修改,出现错误只能修正,或者测试排除;异常指的是在程序执行过程中出现不合理的或者上下文对应不上的语法和逻辑问题,注意这里不是指语法和逻辑错误。
下面先简单的演示几种常见的异常。
# 1.除零异常:ZeroDivisionError
# 5/0
# 2.名称异常:NameError
# print(name)
# 3.类型异常:TypeError
# '1' + 2
# 4.索引异常:IndexError
# l = [1, 2]
# l[3]
# 5.键异常:KeyError
# dic = {'a': 'lucy', 'b': 'tom'}
# dic['b']
# 6.值异常:ValueError
# int('aaa')
# 7.属性异常:AttributeError
# name = 'Tom'
# print(name.xx)
# 8.迭代器异常:StopIteration
# lis = iter([1, 2, 3])
# print(next(lis))
# print(next(lis))
# print(next(lis))
# print(next(lis))
下面是python异常的继承关系
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