错误
- 语法错误/编译错误 synataxError
编译器编译时的错误,编译器会提示行号和信息 - 运行错误
解释执行中出现的错误 - 逻辑错误
执行不报错,但是结果不正确。是由于人的错误
异常处理
程序运行时产生错误就会抛出异常对象,程序终止执行正常流程,转而执行异常处理流程
try… except…else…finally中except可以捕获处理异常
应该将派生程度高/更具体的异常类的excpet快放在前面(比如ValueError, IOError等应该放在Exception前面)
不管except中如何,finally中的语句始终会执行;finnaly长用来清理占用资源等
def ReadFile(file:str):
try:#可能抛出异常的代码
f=open(file)
except (FileExistsError,FileNotFoundError):
#创建已经存在的文件,无法打开文件
print("File error")
except PermissionError:
#无读取权限
print("Permission denied")
except Exception:
print("Something")
finally:
f.close()
内置异常类
Python异常类都派生于BaseException
常见异常:
- NameError: 尝试访问为声明变量
- AttributeError: 刚问对象没有的属性
a : int =1
a.show() #AttributeError
- TypeError: 类型错误
11+'abs' #typeerror
- ValueError: 数值错误
int('abc') #ValueError
- IndexError : 索引超出范围
- KeyError: dict的key不存在
自定义异常类
自定义异常类一半继承于Exception或其子类,用raise调用
class NumberError(Exception):
def __init__(self, data):
Exception.__init__(self, data)
self.data = data
def __str__(self) -> str:
return self.data + ': invalid value'
断言处理
断言主要功能是帮助程序员调试程序, 在调试模式时断言有效,优化模式(-O)自动忽视断言
python assert_test.py
python -O assert_test.py
两种形式的assert语句:
assert 布尔表达式,字符串表达式
assert 布尔表达式
布尔表达式为假,则会抛出AssertionError
在优化模式-O 中, __debug__为False
logging模块输入日志
通过logging模块可以在呈现出和库中配置输出消息的级别、配置消息格式和内容、配置输出位置(控制台、文件等)
一般配置流程:
**创建logger -> 创建Handler -> 创建formater对象 -> formater对象和Handler关联 -> Handler添加到logger-> 调用logger
- logger: 日志接口,创建logger对象
- handler: 日志处理器。一个logger可以通过addHandler配置多个Handler。Handler中可以定义level, file
- Filer: 日志过滤器。 每个Handler可以对应一个filer
- formatter : 日志格式化。包括两个参数:消息格式字符串和日期字符串
关于level设置
从严重性以上到下分为一下几类:
- Emergency (emerg): indicates that the system is unusable and requires immediate attention.
- Alert (alert): indicates that immediate action is necessary to resolve a critical issue.
- Critical (crit): signifies critical conditions in the program that demand intervention to prevent system failure.
- Error (error): indicates error conditions that impair some operation but are less severe than critical situations.
- Warning (warn): signifies potential issues that may lead to errors or unexpected behavior in the future if not addressed.
- Notice (notice): applies to normal but significant conditions that may require monitoring.
Informational (info): includes messages that provide a record of the normal operation of the system. - Debug (debug): intended for logging detailed information about the system for debugging purposes.
设置level可以参考(https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels):
import logging
#创建logger
logger = logging.getLogger('oj0404')
logger.setLevel(logging.DEBUG)
#创建file handler
fh = logging.FileHandler('logging_test.txt')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname) - %(message)s')
fh.setFormatter(formatter)
#创建控制台consolo handler
console = logging.StreamHandler()
console.setLevel(logging.ERROR)
#handler添加到logger
logger.addHandler(fh)
logger.addHandler(console)
#调用logger
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')
还可以通过logging.basicConfig()更便携地配置
logging.basicConfig(filename='logging_test.txt', level=logging.DEBUG,format='%(asctime)s - %(name)s')
logging.debug("debug message")
logging.info("info message")