Python exception handling and debugging
Python provides a powerful exception handling mechanism, can improve the robustness of the program by capturing exceptions. Exception handling has also released an object, such as suspension of the role of the cycle of operation. The program is running, if an error occurs, you can return an error code prior agreement.
"Try ... except" statement
To deal with the problem statement, catch exceptions may exist. try block placed in clause exception statements may occur, except clause code for handling exceptions. When an exception occurs, Python will automatically generate an exception object.
>>> try:
... f = open('test.txt', 'r')
... print("该文件是正常的")
# 捕获IO异常
... except IOError:
... print("该文件不存在")
# 其他异常情况
... except:
... print('程序异常')
... else:
... print('文件打开成功')
f.close()
该文件不存在
>>>
try...except
You can also add back a finally
statement, regardless of whether an exception occurs, the finally
clause will be executed. All finally
clauses are used to turn off the system resources can not be released due to an exception.
try:
f = open('test.txt', 'r')
try:
print(f.read())
except:
print('该文件是正常的')
finally:
print('释放资源')
f.close()
except IOError:
print('文件不存在')
with...as
with...as
(Context tube) may achieve the above functions very simple
with open('test.txt', 'r') as f:
f.write('hrllo ')
f.write('world ')
with...as
Circumstances can handle unusual circumstances, and avoids open () after a file forget to close () method
raise
When a program error occurs, Python will automatically raise an exception, can also raise
exception that is thrown display statement, once executed raise
statement, raise
the code after the statement will not be executed
try:
s = None
if s is None:
print('s是空对象')
raise NameError
print(len(s))
except TypeError:
print('空对象是没有长度的')
s是空对象
Traceback (most recent call last):
File "异常处理.py", line 21, in <module>
raise NameError
NameError
Python debugging
General debugging method used
- print method
- Assertion (assert) method
- logging module
- pdb
- Editor comes with debugging features
Assertion (assert) method for detecting whether an expression is true
>>> assert 1 == 0, '1 不等于 0' # '1 不等于 0' 是为断言语句加的异常参数
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: 1 不等于 0
>>>
logging module
If the Python program code amount to a certain number, use the logging module is a good choice, logging can not only output to the console, you can also write to the file, TCP send the logs to the network can also be used.
import logging
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')
# 输出结果:
WARNING:root:warning message
ERROR:root:error message
CRITICAL:root:critical message
By default, logging module logs print to the screen (stdout), log level is WARNING (only WARNING log level is higher than the output of the log will)
pdb
Python debugger that allows single-step program execution, at any time to view the running status
carried outpython3 -m pdb test.py
"L" represents the code for the full experience, "n" represents a step by step through the code, "p + variable name" variable names can print out the program at any time, "q" to exit