How To Ignore Exceptions While Looping?
Solution 1:
Quick solution:
Catching the exceptions inside your loop.
for i inrange(10):
try:
# Do kucoin stuff, which might raise an exception.except Exception as e:
print(e)
pass
Adopting best practices:
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 inrange(10):
try:
# Do kucoin stuff, which might raise an exception.except (KucoinAPIException, KucoinRequestException, KucoinResolutionException) as e:
print(e)
pass
We can make the except clause less verbose by refactoring your custom exception hierarchy to inherit from a custom exception class. Say, KucoinException
.
classKucoinException(Exception):
passclassKucoinAPIException(KucoinException):
# ...classKucoinRequestException(KucoinException):
# ...classKucoinResolutionException(KucoinException):
# ...
And then your loop would look like this:
for i inrange(10):
try:
# Do kucoin stuff, which might raise an exception.except KucoinException as e:
print(e)
pass
Solution 2:
Exception
classes aren't designed to handle exceptions. They shouldn't actually have any logic in them. Exception classes essentially function like enums
to allow us to quickly and easily differentiate between different types of exceptions.
The logic you have to either raise or ignore an exception should be in your main code flow, not in the exception itself.
Solution 3:
You can use finally block to execute the block no matter what.
for i inrange(10):
try:
#do somethingexcept:
#catch exceptionsfinally:
#do something no matter what
Is that is what you were looking for?
Solution 4:
use try except in main block where KucoinAPIException is thrown
for i inrange(10):
try:
# do kucoin stuff# .# .# .except:
pass
Since you mentioned ignoring exceptions I am assuming you would pass all exceptions. So no need to mention individual exceptions at except:
line.
Post a Comment for "How To Ignore Exceptions While Looping?"