user7249782
user7249782

Reputation: 33

How to ignore exceptions while looping?

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)

And this doesn't work:

from kucoin.exceptions import KucoinAPIException, KucoinRequestException, KucoinResolutionException

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

Upvotes: 1

Views: 830

Answers (4)

ndmeiri
ndmeiri

Reputation: 5029

Quick solution:

Catching the exceptions inside your loop.

for i in range(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 in range(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.

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

Upvotes: 2

Morse
Morse

Reputation: 9115

use try except in main block where KucoinAPIException is thrown

for i in range(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.

Upvotes: -2

Brendan Abel
Brendan Abel

Reputation: 37499

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.

Upvotes: 1

Piotr Lachert
Piotr Lachert

Reputation: 24

You can use finally block to execute the block no matter what.

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

Is that is what you were looking for?

Upvotes: 0

Related Questions