Step 1 - A simple example

In python, we handle exceptions using a block called a try-except which wraps around our code. Python uses the try statement to attempt to run the code and uses the except statement if the code returns some sort of error.

The python documentation provides details on how to implement this. As before we will start with a simple example to illustrate how this works. In this example, we are going to generate a TypeError and handle it with a try-except block.

  • Create a new file called lab_9_step_1_errors.py and add the following code:
integer = 50
string = "The number is"

print(string + integer)

Hopefully, you can see the issue with this code.

  • To run the program, enter the following command in your terminal:

    python lab_9_step_1_errors.py

Check the result

With this example, we are going to add the try-except block.

  • Modify your code to add the try-except.
import logging

integer = 50
string = "The number is"

try:
    print(string + integer)
except TypeError as err:
    logging.warning("Error - {}. You cannot add a string to an integer, without converting the integer to a string first".format(err))

This should return:

WARNING:root:Error - must be str, not int. You cannot add a string to an integer, without converting the integer to a string first

What we did

  1. We have imported logging.

  2. We have added a try-except block to our code.

  3. In the except we have specified what action to take in the event of a TypeError.

  4. We have provided a logging.warning() statement that returns the error message, and also some more meaningful information.

  5. Because we have not provided logging with a logging.basicConfig() it is returning the logging to the console.

What python did (from the documentation)

  1. First, the try clause (the statement(s) between the try and except keywords) is executed.

  2. If no exception occurs, the except clause is skipped and execution of the try statement is finished.

  3. If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.

  4. If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops.

Adding Multiple Except Statements

The except statement above will only work for a TypeError because we have specified this in the except statement.

There can be multiple except statements which provide details on what to do in the event of different types of error.

Here is an example:

import logging

integer = 50
string = "The number is"

try:
    print(string + integer)
except TypeError as t_err:
    logging.warning("Error - {}. You cannot add a string to an integer, without converting the integer to a string first".format(t_err))
except ValueError as v_err:
    logging.warning("Error - {}. Your message".format(v_err))

Exceptions generated by AWS Boto3

We want to be able to see exceptions generated by the AWS services we are calling. These are returned by Boto3 using botocore. We need to add an import statement into our code and then we can use the try-except statement. An example is shown below:

import logging
import boto3
from botocore.exceptions import ClientError

try:
    client = boto3.client('translate')
    <snip>
except ClientError as e:
    logging.warning("<your msg> {}".format(e))

In this step, we have learned how to use the try-except statements to add exception handling to our code. We have also learned how to get boto3 to give us error messages. In the next step, we add try-except to our main code.