错误检测
由于所有过程都要有错误检测,所以把错误检测放到了最前面来编写
分析
原书中使用了标志位es来表示错误类型:标志位为0时没有错误,大于0时产生错误,并用es的值来表示不同错误。
笔者最初使用类似方法,但是是通过返回字符串的形式,但这样显得很繁琐。这在词法分析中不明显,但语法分析时就比较明显了。
例如:
def declaration_list():
...
d = declaration()
if type(d) == str:
return d
...
def declaration():
...
if ...:
return '发生错误'
...
当发生错误时需要一级级返回,最后返回到主函数去处理错误。于是笔者采取了抛异常的方式去处理错误。
def declaration():
...
if ...:
raise MyException("发生错误")
...
...
try():
main()
except MyException as e:
print(e)
改进
当接收到抛出错误信息后,我很难确定错误在哪发生,于是添加了错误路径的确定。详细见code。
myexception.py
global func_path
# 函数路径
func_path = []
def func_path_append(func):
func_path.append(func)
def func_path_remove():
func_path.pop()
# 修饰器 调用函数时添加进路径 结束时逐出路径
def error_path(func):
def run(*args):
func_path_append(func.__name__)
if args:
ret = func(args)
else:
ret = func()
func_path_remove()
return ret
return run
# 错误异常
class MyException(BaseException):
def __init__(self, messege):
self.messege = messege
def __str__(self):
show = ''
for path in func_path:
show += path + ':\n '
show += self.messege
return show