class sexExcption(Exception):
'''
自定义异常类
'''
pass
try:
sex=input('请输入性别:')
if sex!='男' and sex!='女':
raise Exception('性别只能是男或女')
except sexExcption as ex:
print(ex)
except Exception as ex:
print(ex)
finally:
print('程序结束')
日志相关概念 用来记录程序中 重要的消息
日志对象 属性 错误级别
DEBUG
INFO
WARNING
ERROR
CRITICAL
import logging
logging.debug("this is a debug")
logging.info("this is a info")
logging.warning("this is a warning")
logging.error("this is a error")
logging.critical("this is a critical")
数据出结果:
WARNING:root:this is a warning
ERROR:root:this is a error
CRITICAL:root:this is a critical
#
因为debug,info级别太低,所以不显示
import logging
log_format='%(asctime)s- %(levelname)s- %(message)s' #日期 级别 信息
DATE_FORMAT ="%m/%d/%Y %H:%M:%S %p"
logging.basicConfig(level=logging.DEBUG,
filename='my.log',
format=log_format,
datefmt=DATE_FORMAT)
logging.debug("this is a debug")
logging.info("this is a info")
logging.warning("this is a warning")
logging.error("this is a error")
logging.critical("this is a critical")
输出结果:月日年时分秒形式
05/23/2018 22:28:25 PM- DEBUG- this is a debug
05/23/2018 22:28:25 PM- INFO- this is a info
05/23/2018 22:28:25 PM- WARNING- this is a warning
05/23/2018 22:28:25 PM- ERROR- this is a error
05/23/2018 22:28:25 PM- CRITICAL- this is a critical
import logging
log_format='%(asctime)s- %(levelname)s- %(message)s' #日期 级别 信息
DATE_FORMAT ="%Y-%m-%d "
logging.basicConfig(level=logging.DEBUG,
filename='my.log',
format=log_format,
datefmt=DATE_FORMAT)
logging.debug("this is a debug")
logging.info("this is a info")
logging.warning("this is a warning")
logging.error("this is a error")
logging.critical("this is a critical")
输出结果在
my.log中显示:年月日形式
2018-05-23 - DEBUG- this is a debug
2018-05-23 - INFO- this is a info
2018-05-23 - WARNING- this is a warning
2018-05-23 - ERROR- this is a error
2018-05-23 - CRITICAL- this is a critical