我想捕获一个NameError,然后访问该名称并使用它来提供更好的消息。如何在不解析错误消息的情况下访问导致错误的名称?
try:
love_bug = herbie
except NameError as err:
name = get_name(err)
print(name, 'unknown.')
换句话说,如何在上面的代码中实现get_name()?
答案 0 :(得分:2)
您必须从NameError.args[0]
:
>>> try:
... print(foo)
... except NameError as e:
... print(re.search("'(?P<name>.+?)'", e.args[0]).group('name'))
...
foo
答案 1 :(得分:1)
def get_name(err):
last = err.find("' ")
return err[6:last]
try:
love_bug= heribie
except NameError as err:
print(get_name(err.args[0]), "unknown")
答案 2 :(得分:0)
如果我理解你的问题,你可以创建自己的错误,如下:
class ValidateName(NameError):
def __init__(self, name):
# Call the base class constructor with the parameters it needs
super().__init__(self, "unknown name " + name) #or whatever you need to add
try:
love_bug = "herbie"
raise ValidateName(love_bug) #there is no point in raising the exception manually here, I did this only to show how the message is shown,obliviously somewhere in your code the exception is raised
except ValidateName as err:
print(err)
(ValidateName(...),'unknown name herbie')