如何创建自定义异常?

时间:2019-04-23 20:17:11

标签: python python-2.7 exception

我正在尝试根据收到的错误创建自定义异常。这是我的代码:

import boto3
from botocore.exceptions import ClientError, ProfileNotFound
try:
    login_profile = client.get_login_profile(UserName=user_name)
    login_profile = (login_profile['LoginProfile']['UserName'])
except Exception as e:
    print("Exception", e)

这给了我以下输出:

Exception An error occurred (NoSuchEntity) when calling the GetLoginProfile operation: Login Profile for User tdunphy cannot be found.

我尝试添加该错误作为例外,但没有成功:

try:
    login_profile = client.get_login_profile(UserName=user_name)
    login_profile = (login_profile['LoginProfile']['UserName'])
except NoSuchEntity:
    print("The login profile does not exist.")
except Exception as e:
    print("Exception", e)

给我这些错误:

botocore.errorfactory.NoSuchEntityException: An error occurred (NoSuchEntity) when calling the GetLoginProfile operation: Login Profile for User tdunphy cannot be found.
During handling of the above exception, another exception occurred:
NameError: name 'NoSuchEntity' is not defined

并使用此异常:

except NoSuchEntityException:

给我这个错误:

NameError: name 'NoSuchEntityException' is not defined

如何为该错误创建例外?

3 个答案:

答案 0 :(得分:2)

除了ClientErrorProfileNotFound之外,还输入此异常的名称:

import boto3
from botocore.exceptions import ClientError, ProfileNotFound, NoSuchEntityException


try:
    login_profile = client.get_login_profile(UserName=user_name)
    login_profile = (login_profile['LoginProfile']['UserName'])
except NoSuchEntityException:
    print("The login profile does not exist.")
except Exception as e:
    print("Exception", e)

答案 1 :(得分:1)

您只需要定义NoSuchEntityException。示例:

class NoSuchEntityException(Exception):
    def __init__(self):
        self.message = "No Such Entity Exception."

或者在您未导入的其他模块中定义了NoSuchEntityException。

编辑:

我认为这可能是您追求的目标

import boto3

client = boto3.client('sampleText')
try:
    pass
except client.exceptions.NoSuchEntityException:
    pass

答案 2 :(得分:0)

except将捕获特定的Exception类。这意味着需要定义用except处理的异常。如您所述,exceptions中的goto模块还包含NoSuchEntityException,因此请相应地导入和使用:

from goto.exceptions import ClientError, ProfileNotFound, NoSuchEntityException

try:
    login_profile = client.get_login_profile(UserName=user_name)
    login_profile = (login_profile['LoginProfile']['UserName'])

except NoSuchEntityException as e:
    print("Profile isn't found!")
    # do something or exit

except Exception as e:
    raise # Don't know what to do yet, so don't handle this

如果必须 子类,则可以使用基类Exception

class NoSuchEntitiyException(Exception):
    def __init__(self):
        self.message = "No such entity"

try:
    #code
except NoSuchEntityException:
    # do something

请注意,在print子句中使用except可能会导致问题,因为程序仍将继续前进:

try:
    raise ValueError("test error")
    x = 5
except ValueError:
    print("Got a value error!")

print(x)
# NameError: x is not defined