尝试并排除-pythonbot3
我为这个基本问题道歉。我对AWS和Python都是全新的。 我正在尝试执行下面给出的示例代码:尝试并排除-pythonbot3,python,amazon-web-services,boto3,Python,Amazon Web Services,Boto3,我为这个基本问题道歉。我对AWS和Python都是全新的。 我正在尝试执行下面给出的示例代码: import boto3 from botocore.exceptions import ClientError def lambda_handler(event, context): try: ec2 = boto3.resource('ec2') instance=ec2.create_instances(ImageId='ami-d834aba1',
import boto3
from botocore.exceptions import ClientError
def lambda_handler(event, context):
try:
ec2 = boto3.resource('ec2')
instance=ec2.create_instances(ImageId='ami-d834aba1', MinCount=1, MaxCount=1)
except ClientError as e:
print(e)
else:
print(instance)
这是创建ec2实例的示例代码。我从两个文档中复制了相同的内容。
有人能给我解释一下try和功能以外的功能吗。
我需要对完整的代码有一个清晰的理解 Try和Except是Python内置的异常处理检查。Try的意思是“尝试这样做”,而您的异常是捕获任何可能导致程序暂停/出错的异常 通常,异常用于“处理”不希望程序停止执行的情况。人们添加这些异常是为了让他们的程序在不同的错误场景中执行不同的操作。让我们对您的代码进行注释:
def lambda_handler(event, context):
try: #do this first
ec2 = boto3.resource('ec2')
instance=ec2.create_instances(ImageId='ami-d834aba1', MinCount=1, MaxCount=1)
except ClientError as e: #if you see a ClientError, catch it as e
print(e) #print the client error info to console
else: #if everything goes as expected
print(instance) #print my successful instance info
更常见的是,我看到人们使用try-except块,如下所示:
def make_breakfast(ingredients):
try:
if ingredients contain "bacon":
breakfast = cook(bacon)
return breakfast
except NoBaconInIngredients:
ingredients.append("bacon")
make_breakfast(ingredients)
如果您想深入了解这一点,Python文档非常有用。查看此链接:因此代码工作正常,您只想知道逻辑,对吗?