Python 如何更准确地定位异常?

Python 如何更准确地定位异常?,python,python-3.x,exception,Python,Python 3.x,Exception,考虑下面的代码(为了示例而压缩): import ics import arrow import requests a = min(list(ics.Calendar(requests(get('http://asitewithcalendar.org').text).timeline.on(arrow.now()))) 这里发生了很多事情,我对导致代码崩溃的问题(连接、URL问题等)很满意,但不会出现以下错误: ValueError: min() arg is an empty seque

考虑下面的代码(为了示例而压缩):

import ics
import arrow
import requests

a = min(list(ics.Calendar(requests(get('http://asitewithcalendar.org').text).timeline.on(arrow.now())))
这里发生了很多事情,我对导致代码崩溃的问题(连接、URL问题等)很满意,但不会出现以下错误:

ValueError: min() arg is an empty sequence
我想捕捉那个特定的错误:提供给
min()
的是一个空序列(并且
pass
)。更具体地说,我希望其他异常崩溃,包括与馈送到
min()的空序列无关的
ValueError
异常

一个简单的
try
捕获
ValueError
对于除最后一个约束之外的一切都是好的

当错误为
min()arg为空序列时,是否有办法说“除了
ValueError
”?



注意:我知道我的示例中的代码很难看-我写它是为了展示我的问题,因此如果唯一的答案是“不可能-您必须重写它以精确定位您想要尝试的行”,那么就可以了,否则我正在寻找通用解决方案

您可以执行以下操作:

try:
   # Put your code to try here
   a = min(list(ics.Calendar(requests(get('http://asitewithcalendar.org').text).timeline.on(arrow.now())))

except ValueError as e:
    if str(e) == 'min() arg is an empty sequence':
        pass
    else:
        raise e

在这种情况下,我只需在调用
min
之前检查值,而不是等待异常。没有表达式级别的方法来处理异常

foo = list(ics.Calendar(requests(get('http://asitewithcalendar.org').text).timeline.on(arrow.now()))
if foo:
    a = min(foo)
如果
foo
为空,则仍需决定
a
应该是什么,但是
try
语句也会有同样的问题:

foo = list(ics.Calendar(requests(get('http://asitewithcalendar.org').text).timeline.on(arrow.now()))

try:
    a = min(foo)
except ValueError:
    ???
我也不会太担心只处理空序列错误。即使是不同的
ValueError
a
也是未定义的。

这如何

import numpy

a = min(list(ics.Calendar(requests(get('http://asitewithcalendar.org').text).timeline.on(arrow.now())) + [-np.inf])
-inf
返回时。列表中没有任何内容