最大递归深度错误只是另一个异常;您可以捕获^{} exception(Python 3.5或更高版本):try:
solveMaze(maze)
except RecursionError as re:
print('Sorry but this maze solver was not able to finish '
'analyzing the maze: {}'.format(re.args[0]))
我已经合并了附加到运行时异常的错误消息;对于递归错误是maximum recursion depth exceeded。
如果需要支持早于3.5的Python版本,可以捕获基类^{}。如果您担心捕获而不是递归深度错误的运行时错误,那么您可以内省.args[0]值:try:
solveMaze(maze)
except RuntimeError as re:
if re.args[0] != 'maximum recursion depth exceeded':
# different type of runtime error
raise
print('Sorry but this maze solver was not able to finish '
'analyzing the maze: {}'.format(re.args[0]))
选项演示:>>> def infinity(): return infinity()
...
>>> try:
... infinity()
... except RecursionError as re:
... print('Oopsie: {}'.format(re.args[0]))
...
Oopsie: maximum recursion depth exceeded
>>> def alter_dict_size():
... dct = {'foo': 'bar'}
... for key in dct:
... del dct['foo']
...
>>> try:
... alter_dict_size()
... except RuntimeError as re:
... print('Oopsie: {}'.format(re.args[0]))
...
Oopsie: dictionary changed size during iteration
>>> try:
... infinity()
... except RuntimeError as re:
... if re.args[0] != 'maximum recursion depth exceeded':
... raise
... print('Oopsie: {}'.format(re.args[0]))
...
Oopsie: maximum recursion depth exceeded
>>> try:
... alter_dict_size()
... except RuntimeError as re:
... if re.args[0] != 'maximum recursion depth exceeded':
... raise
... print('Oopsie: {}'.format(re.args[0]))
...
Traceback (most recent call last):
File "", line 2, in
File "", line 3, in alter_dict_size
RuntimeError: dictionary changed size during iteration
改变字典大小也会引发RuntimeError异常,但是测试生成的异常消息允许您区分。