给出来自瓶塞(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
上述方法适用于AAAException
或AssertionError
的条件处理,但是可以根据原始代码块中定义的方案(伪代码)进一步完善该处理:
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
答案 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