【问题标题】:How to target an Exception more accurately?如何更准确地定位异常?
【发布时间】:2020-09-08 12:25:48
【问题描述】:

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

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 就可以了)。更具体地说,我希望其他异常崩溃,包括 ValueError 与提供给 min() 的空序列无关的异常。

一个简单的try 捕获ValueError 将适用于除了最后一个约束之外的所有内容。

有没有办法说“当错误为min() arg is an empty sequence 时除外ValueError”?


注意:我知道我的示例中的代码很丑 - 我写它是为了展示我的问题,所以如果唯一的答案是“不可能 - 你必须重写它以查明你想要 try 的行" 那么好吧,否则我正在寻找通用解决方案

【问题讨论】:

    标签: python python-3.x exception


    【解决方案1】:

    你可以这样做:

    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
    

    【讨论】:

      【解决方案2】:

      在这种情况下,我会在调用 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:
          ???
      

      我也不会太担心处理空序列错误。即使是不同的ValueErrora 也一样未定义。

      【讨论】:

        【解决方案3】:

        这个怎么样。

        import numpy
        
        a = min(list(ics.Calendar(requests(get('http://asitewithcalendar.org').text).timeline.on(arrow.now())) + [-np.inf])
        

        -inf 返回时。列表里面什么都没有。

        【讨论】:

          猜你喜欢
          • 2011-03-15
          • 2019-03-03
          • 2019-02-24
          • 1970-01-01
          • 2012-03-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多