异常简介(Built-in Exceptions)
当检测到一个错误时,解释器就无法继续执行了,反而出现了一些错误的提示,这就是所谓的"异常"
在 python
中,所有的异常都派生自 BaseException
类,它是所有异常的 基类
。内置异常类可以被子类化以定义新的异常,如果我们需要自定义一个异常,我们应该从 [Exception
] 类或它的某个子类而不是从 [BaseException
] 来派生新的异常
In Python, all exceptions must be instances of a class that derives from [
BaseException
]. In a [try
] statement with an [except
] clause that mentions a particular class, that clause also handles any exception classes derived from that class (but not exception classes from which it is derived). Two exception classes that are not related via subclassing are never equivalent, even if they have the same name.(在 Python 中,所有异常必须为一个派生自 [
BaseException
]的类的实例。 在带有提及一个特定类的 [except
]子句的 [try
]语句中,该子句也会处理任何派生自该类的异常类(但不处理 它 所派生出的异常类)。 通过子类化创建的两个不相关异常类永远是不等效的,既使它们具有相同的名称)
该文档主要参考以下资料:
① Built-in Exceptions — Python 3.9.5 documentation
② warnings — Warning control — Python 3.9.5 documentation
异常的层次结构
python
中的异常分为 4
种类型,它们都继承自 BaseException
异常类型 | 异常介绍 |
---|---|
SystemExit | 程序意外退出异常 |
KeyboardInterrupt | 用户按下中断键键异常,通常为 Control-C 或 Delete |
GeneratorExit | 生成器被关闭引发的异常 |
Exception | 所有内置的非系统退出类异常都派生自此类, 所有用户自定义异常也应当派生自此类 |
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
异常的捕获
-
捕获异常说明
用户代码可以引发内置异常。 这可被用于测试异常处理程序或报告错误条件,“就像” 在解释器引发了相同异常的情况时一样;但是请注意,没有任何机制能防止用户代码引发不适当的错误,所有的异常捕获都是在猜测某段代码可能会发生异常
-
捕获异常的语法
try: 可能发生错误的代码 except: 如果出现异常执行的代码
-
捕获异常的使用
① 捕获所有继承自
Exception
的异常try: a = 1 / 0 except Exception: print('除法或取余运算的第二个参数不能为零!')
③ 捕获指定的异常
try: print(1/0) except ZeroDivisionError: print('除法或取余运算的第二个参数不能为零!')
③ 捕获多个指定的异常
try: print(1/0) except (NameError, ZeroDivisionError): print('除法或取余运算的第二个参数不能为零!')
异常的流程控制
else
没有异常发生时的操作
try:
print(1)
except Exception as result:
print(result)
else:
print('没有发生异常!')
-
finally
异常发生后也会执行的操作finally
表示的是无论是否异常都要执行的代码,例如关闭文件try: f = open('test.txt', 'r') except Exception as result: f = open('test.txt', 'w') else: print('没有异常,真开心') finally: f.close()
自定义并抛出一个异常
-
引发一个自定义或内置异常
# 引发一个内置异常 raise FileExistsError # 引发一个内置异常 ex = Exception('这是一个内置异常!') raise ex
-
自定义一个派生自
Exception
的异常类class ShortInputError(Exception): """ 自定义异常类,继承Exception 检查用户的输入长度 """ def __init__(self, length, min_len): self.length = length self.min_len = min_len # 设置抛出异常的描述信息 def __str__(self): return f'你输入的长度是{self.length}, 不能少于{self.min_len}个字符' if __name__ == '__main__': try: password = input('请输入你的密码!') if len(password) < 6: raise ShortInputError(len(password), 6) except ShortInputError as result: print(result) else: print('密码输入符合规范!')