Home > Blockchain >  Execute a class only if a condition is met in a try statement
Execute a class only if a condition is met in a try statement

Time:06-27

I want to execute a specific class if a condition is met. If my first condition is met in my try statement, I want to run the code below class bothnotexist and ignore the other class. If my second condition is met, I want to run the code below class usernotexist and ignore the other class. Do you know how to handle that ?

class bothnotexist(Exception):
   print('the user and the service connection do not exist')
   # some actions here

class usernotexist(Exception):
   print('the user does not exist but the service connection exists')
   # some actions here

def lambda_handler(event, context):

   client = boto3.client('iam')
   client.get_user(UserName='Tom') 
   try:
      if client.exceptions.NoSuchEntityException and 'Test05' not in name:
         raise bothnotexist('both do not exist, raise class bothdonotexist')
       if client.exceptions.NoSuchEntityException and 'Test05' in name:
          raise usernotexist(' user does not exist, raise class usernotexist')
   except:
      print ('no action required')

CodePudding user response:

You want to print the statement when you raise your custom exception?

I think overriding the __init__() method will work.

class bothnotexist(Exception):
   def __init__(self):
       print('the user and the service connection do not exist')

CodePudding user response:

The print stament is not necessary.

You can do just this:

class bothnotexist(Exception):
    pass

class usernotexist(Exception):
    pass

def lambda_handler(event, context):
   client = boto3.client('iam')
   client.get_user(UserName='Tom') 
   try:
      if client.exceptions.NoSuchEntityException and 'Test05' not in name:
         raise bothnotexist('both do not exist, raise class bothdonotexist')
       if client.exceptions.NoSuchEntityException and 'Test05' in name:
          raise usernotexist(' user does not exist, raise class usernotexist')
   except:
      print ('no action required')
  • Related