Home > Software engineering >  How to handle try and exception in python for bucket list empty
How to handle try and exception in python for bucket list empty

Time:09-24

I am trying to handle not none or empty list exception while using boto3. I want to know is there any good way of pythonic code to write this.

try:        
    my_region = os.environ['AWS_REGION']
    if my_region == 'us-east-1':
        try:
            s3 = boto3.client('s3')
            buckets_list = s3.list_buckets()
        except Exception as err:
            logging.error('Exception was thrown in connection %s' % err)
            print("Error in connecting and listing bucket{}".format(err))
        if buckets_list['Buckets']:
            # Search for all buckets.
            for bucket in buckets_list['Buckets']:
            # my code follow to get other things...
            
        else:
            print("Buckets are empty in this region")
    else:
        print("Region not available")
        raise Exception("Exception was thrown in Region")    

except Exception as err:
    logging.error('Exception was thrown %s' % err)
    print("Error is {}".format(err))
    raise err

Is this the right way or any suggestions would help.

CodePudding user response:

Your code is somewhat not detailed enough, at least the beginning of the function should have been shared. Anyway, did you consider:

 try:
          s3 = boto3.client('s3')
         buckets_list = s3.list_buckets()
         print("buckets_list", buckets_list['Buckets'])
    
        print("Error is {}".format(err))
         if buckets_list['Buckets'] is not None: ##Here I am trying to check if buckets are empty
        # Search for all buckets.
        for bucket in buckets_list['Buckets']:
     (your other codes)


except Exception as err:
        logging.error('Exception was thrown in connection %s' % err)

CodePudding user response:

You can use else block of the try except suite. It is useful for code that must be executed if the try clause does not raise an exception.

try:
    s3 = boto3.client('s3')
    buckets_list = s3.list_buckets()
except Exception as err:
    logging.error('Exception was thrown in connection %s' % err)
    print("Error is {}".format(err))
else:
    # This means the try block is succeeded, hence `buckets_list` variable is set.
    for bucket in buckets_list['Buckets']:
        # Do something with the bucket

One issue I am seeing from your code is that, if the list_buckets call is failed there is a chance to get NameError at the line if buckets_list['Buckets'] is not None:. Because buckets_list is undefined if the buckets_list call is failed. To understand this try to run the following snippet :)

try:
    a = (1/0)
except Exception as e:
    print(e)

print(a)
  • Related