如何捕获由调用函数时未设置模块变量引起的错误
所以我有这样的代码
file = "whatever the file path is"
menu= [] #this is a global variable
def ordermenu():
with open(file) as f: # read file
reader = csv.reader(f, delimiter=",")
next(reader, None) #skip the header
def showmenu():
for i in range(len(menu)):
print(menu)
ordermenu()
showmenu()
在此功能中,我需要捕获错误。
注意:我不会将这些全局变量用作参数。
答案 0 :(得分:2)
对于未定义的内容,它称为NameError
。像这样用try
-except
包装代码即可:
try:
b = a+1
except NameError:
print("a not defined")