The concept of exception
When the program is running, if the Python interpreter encounters an error, it will stop the execution of the program and prompt some error messages , which is the exception
The program stops execution and prompts an error message . We usually call this action: throwing an exception
During program development, it is difficult to deal with all special cases . Through exception capture , emergency events can be processed in a centralized manner, thereby ensuring the stability and robustness of the program.
2. Python built-in exceptions
Let's first look at the exception hierarchy:
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
Through the above exception hierarchy, we can clearly see that BaseException is the base class of all exceptions, which are divided into four types: SystemExit, KeyboardInterrupt, GeneratorExit, and Exception. Exception is the base class of all non-system exit exceptions. Python advocates inheriting Exception or its subclasses to derive new exceptions; Exception contains a variety of common exceptions such as: MemoryError (memory overflow), BlockingIOError (IO exception), SyntaxError (syntax error exception)... Details can be found below List:
abnormal | describe |
---|---|
BaseException | Base class for all exceptions |
SystemExit | interpreter request to exit |
KeyboardInterrupt | User interrupts execution (usually by typing ^C) |
Exception | base class for general errors |
StopIteration | iterator has no more values |
GeneratorExit | Generator (generator) exception to notify exit |
StandardError | Base class for all built-in standard exceptions |
ArithmeticError | Base class for all numerical computation errors |
FloatingPointError | floating point calculation error |
OverflowError | Numerical operation exceeds maximum limit |
ZeroDivisionError | divide (or modulo) zero (all data types) |
AssertionError | Assertion statement failed |
AttributeError | Object does not have this property |
EOFError | No built-in input, reaching the EOF marker |
EnvironmentError | Base class for operating system errors |
IOError | I/O operation failed |
OSError | operating system error |
WindowsError | system call failed |
ImportError | Failed to import module/object |
LookupError | Base class for invalid data queries |
IndexError | There is no such index in the sequence (index) |
KeyError | There is no such key in the map |
MemoryError | Out of memory error (not fatal to the Python interpreter) |
NameError | undeclared/initialized object (no properties) |
UnboundLocalError | access uninitialized local variable |
ReferenceError | Weak reference attempts to access objects that have been garbage collected |
RuntimeError | General runtime errors |
NotImplementedError | Method not yet implemented |
SyntaxError | Python syntax error |
IndentationError | Indentation error |
TabError | Mixing Tabs and Spaces |
SystemError | General interpreter system errors |
TypeError | Invalid operation on type |
ValueError | Invalid parameter passed in |
UnicodeError | Unicode related errors |
UnicodeDecodeError | Error in Unicode decoding |
UnicodeEncodeError | Error in Unicode encoding |
UnicodeTranslateError | Error during Unicode conversion |
Warning | base class for warnings |
DeprecationWarning | Warning about deprecated features |
FutureWarning | Warning about future semantic changes of constructs |
OverflowWarning | Old warning about auto-promotion to long |
PendingDeprecationWarning | Warning that features will be deprecated |
RuntimeWarning | 可疑的运行时行为(runtime behavior)的警告 |
SyntaxWarning | 可疑的语法的警告 |
UserWarning | 用户代码生成的警告 |
三、异常处理
Python 程序捕捉异常使用 try/except 语句
try:
语句
语句
except 异常的名称 as 变量名: # 使用as可以将异信息保存到变量中,也可以省略as及其后面的部分
语句
语句
except 异常的名称:
语句
语句
except 异常的名称:
语句
语句
...
else: # else 中的部分会在没有发生异常的情况才执行
语句
语句
finally: # finally中的语句,无论是否发生异常,语句都会执行
语句
语句
try 语句的工作方式为:
-
首先,执行 try 子句 (在 try 和 except 关键字之间的部分);
-
如果没有异常发生, except 子句 在 try 语句执行完毕后就被忽略了;
-
如果在 try 子句执行过程中发生了异常,那么该子句其余的部分就会被忽略;
-
如果异常匹配于 except 关键字后面指定的异常类型,就执行对应的except子句,然后继续执行 try 语句之后的代码;
-
如果发生了一个异常,在 except 子句中没有与之匹配的分支,它就会传递到上一级 try 语句中;
-
如果最终仍找不到对应的处理语句,它就成为一个 未处理异常,终止程序运行,显示提示信息。
其中,else 子句只能出现在所有 except 子句之后,只有在没有出现异常时执行;finally 子句放在最后,无论是否出现异常都会执行。
四、抛出异常
使用 raise 语句允许强制抛出一个指定的异常,要抛出的异常由 raise 的唯一参数标识,它必需是一个异常实例或异常类(继承自 Exception 的类),如:
raise NameError('HiThere')
五、自定义异常
正常来说,Python 提供的异常类型已经满足我们的使用了,但是有时候我们有定制性的需求,我们可以自定义异常类,继承自 Error 或 Exception 类就可以了,看个例子:
#自定义异常类 MyExc
class MyExc(Exception): #继承Exception类
def __init__(self, value):
self.value = value
def __str__(self):
if self.value == 0:
return '被除数不能为0'
#自定义方法
def getNum(n):
try:
if n == 0:
exc = MyExc(n)
print(exc)
else:
print(10 / n)
except:
pass
'''
1、调用 getNum(1),输出结果为:
10.0
2、调用 getNum(0),输出结果为:
被除数不能为0
'''
最后
异常处理用于处理程序错误之外,还有许多应用的地方。如关闭资源、平台兼容、模块导入等。这些使用都是基于对异常处理的实现和机制的理解上,以后我们再一起学习。