简体   繁体   中英

How do I use stack trace to tell me which Exception I should use for Python's try/except

I want to write a Try/Except block that catches the specific error causing this stack trace:

  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

But can't figure out how to determine what the correct Exception is.

I've written the following try/except to get more info:

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

And the result I've gotten is:

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()

But, when I try

Except error,e:

I get the following error message:

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

So, how can I figure out which specific exception to flag?

As the traceback indicates you should use curses.error :

import curses

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

You can check curses.error.mro() for base classes which you could except as well:

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

It does however not inherit from one of the concrete exceptions .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM