Bra*_*rad 2 python sorting exception-handling
我使用以下代码按日期排序字典列表:
try:
value["spotlight"].sort(key=lambda x: datetime.datetime.strptime(x["start"], "%Y%m%d-%H%M"), reverse=True)
except:
logger.info("sort exception")
exc_type, exc_obj, exc_tb = sys.exc_info()
logger.info(exc_type)
logger.info(exc_obj)
logger.info(exc_tb.tb_lineno)
Run Code Online (Sandbox Code Playgroud)
从2月开始,我开始看到这个例外:
<type 'exceptions.ValueError'> day is out of range for month
Run Code Online (Sandbox Code Playgroud)
如何判断哪个字典失败以便我可以调试?
PS - 列表大约有500个元素...
不要使用lambda作为键函数,而是编写一个完整的函数定义.让此函数捕获异常,strptime并使用标识的日期字符串引发自己的异常.
在https://wiki.python.org/moin/HandlingExceptions的指导下,使用评论中的建议将信息添加到现有异常对象
def start_key(x):
d = None
try:
d = x["start"]
return datetime.datetime.strptime(d, "%Y%m%d-%H%M")
except Exception as e:
if d:
e.args += (d,)
raise
value["spotlight"].sort(key=start_key, reverse=True)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
81 次 |
| 最近记录: |