【问题标题】:How to ignore exceptions while looping?循环时如何忽略异常?
【发布时间】:2018-03-14 18:14:47
【问题描述】:

我试图在忽略异常的情况下执行循环。我认为passcontinue 将允许我忽略循环中的异常。我应该把passcontinue 放在哪里?

class KucoinAPIException(Exception):
    """Exception class to handle general API Exceptions
        `code` values
        `message` format
    """
    def __init__(self, response):
        self.code = ''
        self.message = 'Unknown Error'
        try:
            json_res = response.json()
        except ValueError:
            self.message = response.content
            pass            
        else:
            if 'error' in json_res:
                self.message = json_res['error']
            if 'msg' in json_res:
                self.message = json_res['msg']
            if 'message' in json_res and json_res['message'] != 'No message available':
                self.message += ' - {}'.format(json_res['message'])
            if 'code' in json_res:
                self.code = json_res['code']
            if 'data' in json_res:
                try:
                    self.message += " " + json.dumps(json_res['data'])
                except ValueError:
                    pass

        self.status_code = response.status_code
        self.response = response
        self.request = getattr(response, 'request', None)

    def __str__(self):
        return 'KucoinAPIException {}: {}'.format(self.code, self.message)

这不起作用:

from kucoin.exceptions import KucoinAPIException, KucoinRequestException, KucoinResolutionException

for i in range(10):
    # Do kucoin stuff, which might raise an exception.
    continue

【问题讨论】:

  • 你能发布你的堆栈跟踪吗?
  • 好吧,我猜你在循环中捕获了异常。
  • 在抛出 KucoinAPIException 的主块中使用 try catch..即这里 #do kucoin stuff continue
  • 谢谢大家,我回家后要试试这个。手指交叉。

标签: python loops exception


【解决方案1】:

快速解决方案:

在你的循环中捕获异常

for i in range(10):
    try:
        # Do kucoin stuff, which might raise an exception.
    except Exception as e:
        print(e)
        pass

采用最佳做法:

请注意,捕获从Exception 继承的所有异常通常被认为是不好的做法。相反,确定可能引发哪些异常并处理这些异常。在这种情况下,您可能想要处理 Kucoin 异常。 (KucoinAPIExceptionKucoinResolutionExceptionKucoinRequestException。在这种情况下,您的循环应如下所示:

for i in range(10):
    try:
        # Do kucoin stuff, which might raise an exception.
    except (KucoinAPIException, KucoinRequestException, KucoinResolutionException) as e:
        print(e)
        pass

我们可以通过重构自定义异常层次结构以从自定义异常类继承来减少 except 子句的冗长。说,KucoinException

class KucoinException(Exception):
    pass

class KucoinAPIException(KucoinException):
    # ...

class KucoinRequestException(KucoinException):
    # ...

class KucoinResolutionException(KucoinException):
    # ...

然后您的循环将如下所示:

for i in range(10):
try:
    # Do kucoin stuff, which might raise an exception.
except KucoinException as e:
    print(e)
    pass

【讨论】:

  • 谢谢,这很好用!但是,我确实有最后一个问题......有没有办法打印我会收到并仍然循环的错误消息?我想知道它是什么。
  • 太棒了,我是新手,所以在我达到 15 岁之前我不能投票...但当我这样做时会记得你。
【解决方案2】:

Exception 类并非旨在处理异常。他们实际上不应该有任何逻辑。异常类的功能本质上类似于enums,使我们能够快速轻松地区分不同的类型异常。

您必须引发或忽略异常的逻辑应该在您的主代码流中,而不是在异常本身中。

【讨论】:

  • 谢谢,我想我有点过于复杂了
【解决方案3】:

无论如何,您都可以使用 finally 块来执行该块。

for i in range(10):
    try:
        #do something
    except:
        #catch exceptions
    finally:
        #do something no matter what

这就是你要找的吗?

【讨论】:

    【解决方案4】:

    在抛出 KucoinAPIException 的主块中使用 try except

    for i in range(10):
        try:
        # do kucoin stuff
        # .
        # .
        # .
        except:
            pass
    

    既然你提到了忽略异常,我假设你会通过所有异常。因此,无需在except: 行提及个别例外情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-17
      • 2011-03-13
      相关资源
      最近更新 更多