除了在Python中尝试之外,错误仍然会发生
我试图捕捉python中的一个错误,当有人输入AWS帐户名时,该帐户名在系统上没有配置文件除了在Python中尝试之外,错误仍然会发生,python,amazon-web-services,Python,Amazon Web Services,我试图捕捉python中的一个错误,当有人输入AWS帐户名时,该帐户名在系统上没有配置文件 try: aws_account = str(input("Enter the name of the AWS account you'll be working in: ")) except: print("No account exists by that name.") session = boto3.Session(profile_name=aws_account) client
try:
aws_account = str(input("Enter the name of the AWS account you'll be working in: "))
except:
print("No account exists by that name.")
session = boto3.Session(profile_name=aws_account)
client = session.client('iam')
但是,如果我输入了错误的帐户名,错误仍然会发生:
raise ProfileNotFound(profile=profile_name)
botocore.exceptions.ProfileNotFound: The config profile (jf-ruby-dev) could not be found
我做错了什么?还有,如果出现故障,如何让脚本再次提示用户输入帐户名?如注释中所述:将相关代码放入try子句中,并引发特定的异常。可以使用循环再次提示。大概是这样的:
succeeded = False
while not succeeded:
try:
aws_account = input("Enter the name of the AWS account you'll be working in: ")
session = boto3.Session(profile_name=aws_account)
client = session.client('iam')
succeeded = True
except botocore.ProfileNotFound:
print("No account exists by that name.")
因为那一行不是引发异常的那一行。Python
str
和input
永远不会引发botocore.exceptions.ProfileNotFound
异常。您没有包括所有相关的代码,并且忽略了堆栈跟踪的重要部分。您处理input()
和str()
的异常,而不是boto3.Session(…)
或Session.client(…)
。注意:不要只捕获之外的所有异常。异常处理不是口袋妖怪的游戏,你不想也不需要捕捉它们。仅捕获可能引发的异常,例如botocore.ProfileNotFound
input
已返回str
,无需调用str
。这就是输入所做的一切;它没有任何方法或理由来验证您是否输入了有效的AWS帐户。谢谢!成功了。现在我很清楚是什么原因导致了错误以及如何处理它。您可以通过简单地创建一个无限循环(while True
)并在设置客户机后添加一个显式的中断
来摆脱succeed
变量。