Error, debugging
- Error handling:
在程序运行的过程中,如果发生了错误,可以事先约定返回一个错误代码,这样,就可以知道是否有错,以及出错的原因
- try ... except ... finally ... error handling mechanism
Code:
`` `
# exception handling
# try ... except ... finally ...'' '
try: # statement is executed first come try print (10/0) in the block of statements
When we think some of the code may be wrong, you can try to run this code,
if executed wrong, then the following code will not continue, but the error-handling code to jump directly to that except statement block ,
after executing except, if there is finally block, the finally block execute, so far, it is finished.
'' '
Print (10/0)
except the ZeroDivisionError: # try block error, execute block except statement, except statement if the block is not being given the try block is not performed
print ( '! except statement is executed')
finally: # no matter except whether the final will execute the finally block, you can not finally statement
print ( '! finally statement is executed')
Print ( 'test is completed!')
`` `- operation result:
- Record error: Python built-in logging module can easily record the error message
Code:
`` `
# built-in functions logging error messages are logged# Is also a mistake, but after the program finishes printing error message continues, and exit to normal:
def man():
Import logging
DEF do_ZeroError (vaule):
return 10 / vaule
try:
do_ZeroError(0)
except Exception:
logging.exception(Exception)
man()
print('End')
```- operation result:
- Throw an error:
raise
Code:
`` `
# raise throw an error# A custom error, error class inheritance need
print(do_Return(0))
class TestError is (a ValueError):
Pass
DEF do_Return (I):
IF I == 0:
The raise TestError is ( 'wrong!')
Return 10 / I
```
- try ... except ... finally ... error handling mechanism
- Debugging: means to check whether correct operation of the program
- Assertion:
assert
mean, n = 0 expression should be True, otherwise, according to the logic of the program is running, the code behind will certainly be wrong!. - Example:
- logging:
- Example:
- Assertion: