Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/amazon-web-services/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试并排除-pythonbot3_Python_Amazon Web Services_Boto3 - Fatal编程技术网

尝试并排除-pythonbot3

尝试并排除-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',

我为这个基本问题道歉。我对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', 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文档非常有用。查看此链接:

因此代码工作正常,您只想知道逻辑,对吗?