python Exception Handling try Example Summary
- 2021-12-11 07:51:52
- OfStack
Exception handling
Brief introduction
When we write program code, we often hang up the whole program because of a small problem.
What are the benefits of exception handling for our tests, I believe that students who have done automation know that our use cases are executed one by one. For example, there are hundreds of use cases in our programs. If one use case causes a program exception due to data, then all the rest will stop working. In this case, we should throw out the problem caused by this data and handle this exception.
We can use tryexcept to handle exceptions.
Structure
Put the statements that may report errors in try:, and then use except to handle exceptions. Every try must have at least 1 except.
If an error statement may occur, we can know which exceptions to report. After except, we need to keep up with the exception name
You can also use universal exception Exception, which can catch any exception
All the standard exception classes for python: See the end of the article
Example 1: Handling the specified error exception type
If we know what errors will be reported, we can directly catch and handle them, but if the name of the caught exception is incorrect, the program will also report errors.
First, we print an error of not declaring/initializing an object (no attribute), and then print another data that can be executed normally
print(aa)
print('bb')
Print results
Traceback (most recent call last):
File "C:\ Users\ Zhang Tianci\ PycharmProjects\ pythonProject\ test\ lianxi\ 111. py", line 6, in < module >
print(a)
NameError: name 'a' is not defined
Obviously print ("bb") is not executed, so we add try to the part where we may or are known to report an error: and specify NameError as to f variables with except, and print out the error
try:
print(aa)
except NameError as f:
print(f)
print('bb')
Print results
name 'aa' is not defined
bb
As you can see, the program prints out the error message and executes print ("bb")
What if I open a wrong file? I don't know the name of the file opening error. What should I do at this time?
try:
open('ztc.txt','r')
except NameError as f:
print(f)
print('bb')
Print results:
Actually, it is an error file. I can't find the exception name correctly with Nameerror
Traceback (most recent call last):
File "C:\Users\ Zhang Tianci \PycharmProjects\pythonProject\test\lianxi\111.py", line 2, in <module>
open('ztc.txt','r')
FileNotFoundError: [Errno 2] No such file or directory: 'ztc.txt'
See Example 2 when you encounter such a situation
Example 2: Universal exception handling
In Example 1, we said that when we can determine what type of error will be reported, we can specify this error type to handle it. Of course, in many cases, we will encounter many unknown exceptions, and it is impossible to predict all exceptions, so we can directly use the universal exception Exception
try:
open('ztc.txt','r')
except Exception as f:
print(f)
print('bb')
Print results:
exception can handle any error type exception in our try
[Errno 2] No such file or directory: 'ztc.txt'
bb
Example 3: try... finally...
try... finally... means that if our program has encountered an error, the code must be executed
What scenes can be used?
For example, if we link to the database, if we want to operate the database, if the program reports an error or does not report an error, we must close the database
For example, if we open an excel or txt document and want to write data, we must close this document regardless of whether an error is reported or not
First look at a normal execution situation
try:
f = open('ztc.json','r')
finally:
f.close()
print(' Has been closed ')
Print results
Has been closed
If you open the file and report an error before the file is closed,
try:
f = open('ztc.json','r')
print(aaa)
finally:
f.close()
print(' Has been closed ')
Print results
Traceback (most recent call last):
File "C:\ Users\ Zhang Tianci\ PycharmProjects\ pythonProject\ test\ lianxi\ 111. py", line 3, in < module >
print(aaa)
NameError: name 'aaa' is not defined
Has been closed
Look at the above code, obviously the program printed print (aaa) when the error, but will still open the file to close
Appendix:
异常名称 | 描述 |
---|---|
BaseException | 所有异常的基类 |
SystemExit | 解释器请求退出 |
KeyboardInterrupt | 用户中断执行(通常是输入^C) |
Exception | 常规错误的基类 |
StopIteration | 迭代器没有更多的值 |
GeneratorExit | 生成器(generator)发生异常来通知退出 |
SystemExit | Python 解释器请求退出 |
StandardError | 所有的内建标准异常的基类 |
ArithmeticError | 所有数值计算错误的基类 |
FloatingPointError | 浮点计算错误 |
OverflowError | 数值运算超出最大限制 |
ZeroDivisionError | 除(或取模)零 (所有数据类型) |
AssertionError | 断言语句失败 |
AttributeError | 对象没有这个属性 |
EOFError | 没有内建输入,到达EOF 标记 |
EnvironmentError | 操作系统错误的基类 |
IOError | 输入/输出操作失败 |
OSError | 操作系统错误 |
WindowsError | 系统调用失败 |
ImportError | 导入模块/对象失败 |
KeyboardInterrupt | 用户中断执行(通常是输入^C) |
LookupError | 无效数据查询的基类 |
IndexError | 序列中没有没有此索引(index) |
KeyError | 映射中没有这个键 |
MemoryError | 内存溢出错误(对于Python 解释器不是致命的) |
NameError | 未声明/初始化对象 (没有属性) |
UnboundLocalError | 访问未初始化的本地变量 |
ReferenceError | 弱引用(Weak reference)试图访问已经垃圾回收了的对象 |
RuntimeError | 1般的运行时错误 |
NotImplementedError | 尚未实现的方法 |
SyntaxError | Python 语法错误 |
IndentationError | 缩进错误 |
TabError | Tab 和空格混用 |
SystemError | 1般的解释器系统错误 |
TypeError | 对类型无效的操作 |
ValueError | 传入无效的参数 |
UnicodeError | Unicode 相关的错误 |
UnicodeDecodeError | Unicode 解码时的错误 |
UnicodeEncodeError | Unicode 编码时错误 |
UnicodeTranslateError | Unicode 转换时错误 |
Warning | 警告的基类 |
DeprecationWarning | 关于被弃用的特征的警告 |
FutureWarning | 关于构造将来语义会有改变的警告 |
OverflowWarning | 旧的关于自动提升为长整型(long)的警告 |
PendingDeprecationWarning | 关于特性将会被废弃的警告 |
RuntimeWarning | 可疑的运行时行为(runtime behavior)的警告 |
SyntaxWarning | 可疑的语法的警告 |
UserWarning | 用户代码生成的警告 |