[英]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))
如果我用以下方式打印出确切的异常:
except Exception as e then use print(type(e))
This is what I get: 这是我得到的:
The error type is: <class 'botocore.exceptions.ProfileNotFound'>
. 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: from botocore.exceptions import ProfileNotFound
在我的代码中from botocore.exceptions import ProfileNotFound
,然后except botocore.exceptions.ProfileNotFound:
我仍然收到此错误:
except botocore.exceptions.ProfileNotFound: NameError: name 'botocore' is not defined
. except botocore.exceptions.ProfileNotFound: NameError: name 'botocore' is not defined
。
What am I doing wrong? 我究竟做错了什么? How can I except this error specifically?
我如何才能专门排除此错误?
You need to import the exceptions from boto. 您需要从boto导入异常。
from botocore.exceptions import ProfileNotFound
the exceptions won't necessarily be imported by default. 默认情况下,不一定会导入例外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.