捕获Python中的特定异常

时间:2019-04-08 19:01:16

标签: python boto3

如果我捕获到遇到的错误的所有异常,我的脚本就可以正常工作。

但是,如果我尝试将其限制为仅一个异常,这就是我得到的错误:

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

这是我的代码:

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!')

如果我将除外更改为:

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

该程序有效。

这是我要尝试的完整错误,除了:

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

如果我使用以下命令打印出确切的例外情况: except Exception as e then use print(type(e))

这就是我得到的:

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

如果可以的话,

from botocore.exceptions import ProfileNotFound在我的代码中,然后在except botocore.exceptions.ProfileNotFound:中,我仍然收到此错误:

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

我在做什么错?我该如何专门排除此错误?

1 个答案:

答案 0 :(得分:5)

您需要从boto导入例外。

from botocore.exceptions import ProfileNotFound

默认情况下不一定会导入例外。