是否有可能有条件地处理多个不同的AssertionError和Exceptions?

时间:2013-12-03 09:46:17

标签: python-2.7 if-statement assert conditional-statements bottle

给出来自瓶塞(link to code)函数的代码块:

assert username, "Username must be provided."
assert password, "A password must be provided."
assert email_addr, "An email address must be provided."
if username in self._store.users:
    raise AAAException("User is already existing.")
if role not in self._store.roles:
    raise AAAException("Nonexistent role")
if self._store.roles[role] > max_level:
    raise AAAException("Unauthorized role")

我希望以不同的方式处理不同的断言'错误',例如:

try:
    aaa.register(post_get('username'), post_get('password'), post_get('email_address'))
except AAAException as ae:
    #  do something
except AssertionError as aee:
    # do something else

上述方法适用于AAAExceptionAssertionError的条件处理,但是可以根据原始代码块中定义的方案(伪代码)进一步完善该处理:

try:
    aaa.register(post_get('username'), post_get('password'), post_get('email_address'))
except AAAException as ae:
    if AAAException == "User is already existing.":
            # do this
            # etc
except AssertionError as aee:
    if AssertionError == "Username must be provided.":
            # do this
            # etc

1 个答案:

答案 0 :(得分:2)

except区块内

except AssertionError as aee:

抛出的异常对象 instance aee; AssertionError。您需要检查实例的内容:

except AssertionError as aee:
    if "Username must be provided." in aee.args:
        # do your thing