循环时如何忽略异常? [英] How to ignore exceptions while looping?
问题描述
我试图在忽略异常的同时执行循环.我认为pass
或continue
将允许我忽略循环中的异常.我应该在哪里放置pass
或continue
?
I am trying to execute a loop while ignoring exceptions. I think pass
or continue
will allow me to ignore exceptions in a loop. Where should I put the pass
or continue
?
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
推荐答案
快速解决方案:
在循环中 捕获异常.
for i in range(10):
try:
# Do kucoin stuff, which might raise an exception.
except Exception as e:
print(e)
pass
采用最佳做法:
请注意,捕获从Exception
继承的所有异常通常被认为是不好的做法.相反,确定可能引发的异常并处理这些异常.在这种情况下,您可能要处理Kucoin
异常. (KucoinAPIException
,KucoinResolutionException
和KucoinRequestException
.在这种情况下,您的循环应如下所示:
Note that it is generally considered bad practice to catch all exceptions that inherit from Exception
. Instead, determine which exceptions might be raised and handle those. In this case, you probably want to handle your Kucoin
exceptions. (KucoinAPIException
, KucoinResolutionException
, and KucoinRequestException
. In which case your loop should look like this:
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
.
We can make the except clause less verbose by refactoring your custom exception hierarchy to inherit from a custom exception class. Say, KucoinException
.
class KucoinException(Exception):
pass
class KucoinAPIException(KucoinException):
# ...
class KucoinRequestException(KucoinException):
# ...
class KucoinResolutionException(KucoinException):
# ...
然后您的循环将如下所示:
And then your loop would look like this:
for i in range(10):
try:
# Do kucoin stuff, which might raise an exception.
except KucoinException as e:
print(e)
pass
这篇关于循环时如何忽略异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!