14. Exception mechanism

1. Catch abnormal statements, at least try and one expect

example:

try:
    int1 = int(input('请输入一个数字:'))
    print(1/int1)
except ZeroDivisionError:         #捕捉ZeroDivisionError异常
    print('0 不能作为分母')
except ValueError:                #捕捉ValueError异常
    print('你输入的不是数字')
except:                           #捕捉其他异常
    print('程序出现异常')
else:                             #当try完整执行,没有异常时执行else
    print('输入正确')
finally:                          #不论是否有异常,都会执行finally
    print('管你有没有异常,运行结束')


2. Common errors

  • NameError #Undefined
  • IndexError #Subscript out of bounds
  • IOError #Input and output abnormal
  • FileNotFoundError #File does not exist exception

3. Manually throw an exception

try:
    raise FileNotFoundError
except FileNotFoundError:
    print('文件不存在')


4, affirmation

assert 1==int(input('请输入一个数字:'))

When the result is true, the assertion will not do anything. When the result is false, the assertion will take effect.

5. Logging. The
logging module needs to be loaded. The log levels are in order: debug, info, warning, error, critical.

Example:

import logging
import time
import traceback #异常信息显示模块

#level默认为warning,显示设置的level日志级别及以上级别的日志
logging.basicConfig(level='INFO',filename='D:/test02.txt',filemode='a+')

try:
    int1 = int(input('请输入一个数字:'))
    print(1/int1)
except ZeroDivisionError:
    logging.debug(time.strftime('%y-%m-%d %H:%M:%S')+traceback.format_exc()+'debug信息')
    logging.info(time.strftime('%y-%m-%d %H:%M:%S')+traceback.format_exc()+'info信息')
    logging.warning(time.strftime('%y-%m-%d %H:%M:%S')+traceback.format_exc()+'warning信息')
    logging.error(time.strftime('%y-%m-%d %H:%M:%S')+traceback.format_exc()+'error信息')
    logging.critical(time.strftime('%y-%m-%d %H:%M:%S') + traceback.format_exc() + 'critical信息')
    

In the example, the ZeroDivisionError exception is captured, and the log level is set to info.
When the number 0 is entered, the log of info and above levels is recorded in the file, as shown in the following figure:

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45128456/article/details/112281171