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

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

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

  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

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

我编写了以下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

因此,如何确定要标记哪个特定异常?

最佳答案

如回溯所示,您应该使用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之一。

关于python - 我如何使用堆栈跟踪来告诉我应该为Python的try/except使用哪个异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55752445/

相关文章:

python - PhantomJS 看不到由 AJAX 填充的下拉选项

python - 要求django url中变量的最小长度

python - 请帮助我理解 Python 代码

swift - Swift 中的函数错误处理

actionscript-3 - Action : TypeError: Error #1009

delphi - 如何解释 RtlLeaveCriticalSection 中的访问冲突

python - Mac上某些按钮的IDLE崩溃

python - 通过 subprocess.call 向 localhost 发出命令

python - pip安装numpy失败错误代码1

python - 如何从现有数据框创建新数据框?