我有一个自定义异常,我想使用它,类似于下面的。当我处理异常时,我希望我的消息打印错误-即;ShortPasswordError:Luke"-而不仅仅是密码-";卢克";。这就是我所说的。
class AuthenticationError(ValueError):
pass
class ShortPasswordError(AuthenticationError):
pass
def createPassword(password):
if len(password) < 10:
raise ShortPasswordError(password)
password = input("Enter a password: ")
try:
createPassword(password)
except AuthenticationError as e:
print(f"Looks like there's an error with your password. Does {e} ring any bells?")
以下是目前正在发生的事情
Enter a password: Luke
Looks like there's an error with your password. Does Luke ring any bells?
使用repr
而不是str
来格式化f字符串中的异常。
print(f"Looks like there's an error with your password. Does {e!r} ring any bells?")
这将产生
$ python3 tmp.py
Enter a password: Luke
Looks like there's an error with your password. Does ShortPasswordError('Luke') ring any bells?