我如何使用堆栈跟踪来告诉我应该为Python的try / except使用哪个异常

时间:2019-04-18 19:14:51

标签: python python-2.7 error-handling try-except

我想编写一个Try / Except块来捕获导致该堆栈跟踪的 specific 错误:

  File "/home/me/anaconda2/envs/deepnn/lib/python2.7/site-packages/tensorflow/python/debug/wrappers/local_cli_wrapper.py", line 292, in _prep_cli_for_run_start
    self._run_cli = ui_factory.get_ui(self._ui_type)
  File "/home/me/anaconda2/envs/deepnn/lib/python2.7/site-packages/tensorflow/python/debug/cli/ui_factory.py", line 61, in get_ui
    return curses_ui.CursesUI(on_ui_exit=on_ui_exit, config=config)
  File "/home/me/anaconda2/envs/deepnn/lib/python2.7/site-packages/tensorflow/python/debug/cli/curses_ui.py", line 289, in __init__
    self._screen_init()
  File "/home/me/anaconda2/envs/deepnn/lib/python2.7/site-packages/tensorflow/python/debug/cli/curses_ui.py", line 404, in _screen_init
    self._screen_color_init()
  File "/home/me/anaconda2/envs/deepnn/lib/python2.7/site-packages/tensorflow/python/debug/cli/curses_ui.py", line 409, in _screen_color_init
    curses.use_default_colors()
_curses.error: use_default_colors() returned ERR

但是无法弄清楚如何确定什么是正确的异常。

我编写了以下try / except以获得更多信息:

        try:
             ... call to procedure that generates error ...
        except Exception,e:
            print("type is:", e.__class__.__name__)
            import sys
            print(sys.exc_info())

我得到的结果是:

type is: error
(<class '_curses.error'>, error('use_default_colors() returned ERR',), <traceback object at 0x7fdec55abdd0>)
> /home/me/Projects/kerasECOC/net_manager.py(164)init_model_architecture()

但是,当我尝试

Except error,e:

我收到以下错误消息:

  File "/home/me/Projects/kerasECOC/net_manager.py", line 157, in init_model_architecture
    except error,e:
NameError: global name 'error' is not defined

那么,如何确定要标记哪个特定异常?

1 个答案:

答案 0 :(得分:1)

如回溯所示,您应使用curses.error

import curses

try:
    ...
except curses.error as err:
    print(err)

您还可以检查curses.error.mro()中是否可以找到基类,除了:

>>> curses.error.mro()
[<class '_curses.error'>, <class 'Exception'>, <class 'BaseException'>, <class 'object'>]

但是它并不继承自concrete exceptions之一。