1

I have some knowledge of raise-exception, try-catch. but I am not clear how to handle these errors in a right way.

e.g. I created some dymanodb functions in AWS lambda service:

def dynamodb_create_table (table_name, ...):
    table = dynamodb.create_table (...)
    table.wait_until_exists()
    return table

def dyndmodb_get_item (table, ...):
    try:
        response = table.get_item(...)
    except ClientError as e:
        logger.error (e.response['Error']['Message'])
        return  #question: what should I do here
    else:
        return response['Item']

def handler (test):
    table_name = test["table_name"]
    if table_name not in ["test1", "test2"]:
        raise ValueError('table_name is not correct')

    dynamodb = boto3.resource('dynamodb')
    try:
        response = boto3.client('dynamodb').describe_table(...)
    except ClientError as ce:
        if ce.response['Error']['Code'] == 'ResourceNotFoundException':
            logger.info("table not exists, so Create table")
            ddb_create_table (table_name, partition_key, partition_key_type)
        else:
            logger.error("Unknown exception occurred while querying for the " + table_name + " table. Printing full error:" + str(ce.response))
            return # question: what should I do here

 table = dynamodb.Table(table_name)
 ...
 response = ddb_put_item (table,...)
 item = ddb_get_item (table, ...)
 ...

As you can see, sometimes try-except is in called-functions (like dyndmodb_get_item), sometimes the try-except is in calling-functions (handler).

if there is except. I want the lambda exits/stop. then should I exit from called-functions directly, or should I return sth. in called-functions, catch it in calling-function, and then let calling function to exit?

Besides, I found if I use some build-in exception such as ValueError, I do not even need to wrap ValueError with try. etc. if the value is wrong, the function exits. I think it is neat. but this link Manually raising (throwing) an exception in Python put ValueError in a try-except. Anyone know whether it is enough to simply call ValueError or should I wrap it in try-except?

1 Answer 1

3

If you can handle an exception, then you should catch it, make the necessary modifications, then return to what you were doing. If your method is unable to handle the exception, you should raise the exception so that it is passed to the caller. Then, at the topmost calling method to your running instance, you should print a trace or error message if the exception is in fact fatal.

def dynamodb_create_table (table_name, ...):
    table = dynamodb.create_table (...)
    table.wait_until_exists()
    return table

def dyndmodb_get_item (table, ...):
    try:
        response = table.get_item(...)
    except ClientError as e:
        logger.error (e.response['Error']['Message'])
        raise
    else:
        return response['Item']

def handler (test):
    dynamodb = boto3.resource('dynamodb')
    try:
        response = boto3.client('dynamodb').describe_table(...)
    except ClientError as ce:
        if ce.response['Error']['Code'] == 'ResourceNotFoundException':
            logger.info("table not exists, so Create table")
            ddb_create_table (table_name, partition_key, partition_key_type)
        else:
            logger.error("Unknown exception occurred while querying for the " + table_name + " table. Printing full error:" + str(ce.response))
            raise

 table = dynamodb.Table(table_name)
 ...
 response = ddb_put_item (table,...)
 item = ddb_get_item (table, ...)
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks J. Blackadar. what if ddb_get_item (table, ...) return from raise? how will handler() take care of the raise? should handler() wrap ddb_get_item in try-except as well?.
J. Blackadar. and reading your code, looks like if I want to quit, I can just type raise in called function and in calling function.
The calling function will raise the same exception you caught in the callable, and you'll have the opportunity to handle it from that function, or to print an error. To understand this, think of a convenience store purchase where the cashier made the incorrect change for your purchase. The customer raises an IncorrectChangeException, but the cashier cannot do anything about it because she can't open the register. She raises the exception to the manager, who will get the IncorrectChangeException. The manager can then open the drawer with their key, apologize, etc. Same concept applies.
J. Blackadar, Oh, I see. so if the handler() raise, then it will quit at the raise. that is why when I raise ValueError, it quits.
Right, if there is a fatal and uncaught runtime exception it will quit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.