-1

I have multiple exceptions and want to raise a specific exception only if a condition is true. Do you know if it would be possible ?

def lambda_handler(event, context):

    verif = boto3.resource('iam')
    client_iam = boto3.client('iam')
    user = verif.User('Tom')
    try:
        user.load()
        if verif.exceptions.NoSuchEntityException:
            raise Userdoesnotexist
        if ex.response['Error']['Code'] != 'NoSuchEntityException':
            raise Userexists

    except Userdoesnotexist:

    except Userexists:
liyas
  • 7
  • 4
  • It is certainly possible, yes. As explained in the [official Python documentation](https://docs.python.org/3/tutorial/errors.html), you will need to define exception classes inheriting from `BaseException` or its subclasses (e.g., `Exception`) for each of the different types of custom exception you want to raise. – Schol-R-LEA Jun 25 '22 at 14:50

1 Answers1

1

Yes. it should be possible. as an example i found this from the Errors and Exceptions documentation of python.

In this example the exceptions are put on a list. The list is iterated in the for loop and the exceptions are raised one by one..

class B(Exception):
    pass

class C(B):
    pass

class D(C):
    pass

for cls in [B, C, D]:
    try:
        raise cls()
    except D:
        print("D")
    except C:
        print("C")
    except B:
        print("B")

For your purpose maybe it would look something like:

class Userdoesnotexist(Exception):
    def __init__(self, message):            
        # Call the base class constructor with the parameters it needs
        super().__init__(message)

class Userexists(Exception):
    def __init__(self, message):            
        # Call the base class constructor with the parameters it needs
        super().__init__(message)

def lambda_handler(event, context):

    verif = boto3.resource('iam')
    client_iam = boto3.client('iam')
    user = verif.User('Tom')
    try:
        user.load()
        if verif.exceptions.NoSuchEntityException:
            raise Userdoesnotexist("user does not exist.")
        if ex.response['Error']['Code'] != 'NoSuchEntityException':
            raise Userexists("user exist.")

Probably it is not perfect but you could take a look to this thread.

fbzyx
  • 189
  • 1
  • 16