bluethundr
bluethundr

Reputation: 1325

Catch specific exceptions in Python

My script works fine if I catch all exceptions to an error I was experiencing.

However if I try to limit it to just one exception, this is the error I get:

except botocore.ProfileNotFound:
NameError: name 'botocore' is not defined

This is my code:

import boto3
while True:
    try:
        aws_account = input("Enter the name of the AWS account you'll be working in: ")
        session = boto3.Session(profile_name=aws_account)
        resource = session.resource('iam')
        client = session.client('iam')
        kms_client = session.client('kms')
        secrets_client = session.client('secretsmanager')
        break
    except botocore.ProfileNotFound:
        print('AWS account does not exist. Try again!')

If I change the except to:

except:
    print('AWS account does not exist. Try again!')

The program works.

This is the full error that I am trying to except:

 raise ProfileNotFound(profile=profile_name)
botocore.exceptions.ProfileNotFound: The config profile (jf-ruby-dev) could not be found

If I print out the exact exception with: except Exception as e then use print(type(e))

This is what I get:

The error type is: <class 'botocore.exceptions.ProfileNotFound'>.

Yet if I do:

from botocore.exceptions import ProfileNotFound in my code and then except botocore.exceptions.ProfileNotFound:, I am still getting this error:

except botocore.exceptions.ProfileNotFound: NameError: name 'botocore' is not defined.

What am I doing wrong? How can I except this error specifically?

Upvotes: 4

Views: 5704

Answers (1)

dwagon
dwagon

Reputation: 511

You need to import the exceptions from boto.

from botocore.exceptions import ProfileNotFound

the exceptions won't necessarily be imported by default.

Upvotes: 9

Related Questions