首页 > 解决方案 > Python - 在异常中捕获异常?

问题描述

我定义了这个异常:

class ArgumentsException(Exception):
    """Exception that is raised when incorrect arguments are used."""

    pass

现在我运行我的测试,我通过sh包运行我的程序。并且当它引发这个预期的异常时,会sh捕获该异常本身,然后重新引发他自己的异常。有没有办法让我检查我的原始异常是否以某种方式引发?

例如,当我运行此代码时(此代码预计会引发该异常):

sh.python3(
  self.main_py_path,
  self.live_cfg_path,
  self.workflow_cfg_path)

我得到了这个例外:

Traceback (most recent call last):
  File "/home/oerp/src/devops-tools/tests/test_main.py", line 153, in test_full_workflow_1
    self.workflow_cfg_path)
  File "/usr/local/lib/python3.5/dist-packages/sh.py", line 1427, in __call__
    return RunningCommand(cmd, call_args, stdin, stdout, stderr)
  File "/usr/local/lib/python3.5/dist-packages/sh.py", line 774, in __init__
    self.wait()
  File "/usr/local/lib/python3.5/dist-packages/sh.py", line 792, in wait
    self.handle_command_exit_code(exit_code)
  File "/usr/local/lib/python3.5/dist-packages/sh.py", line 815, in handle_command_exit_code
    raise exc
sh.ErrorReturnCode_1: 
  RAN: /usr/bin/python3 /home/oerp/src/devops-tools/main.py /home/oerp/src/devops-tools/tests/configs/__live__.py /home/oerp/src/devops-tools/tests/configs/__workflow__.py

  STDOUT:


  STDERR:
Traceback (most recent call last):
  File "/home/oerp/src/devops-tools/main.py", line 204, in <module>
    state = _get_state(args.state, ignore_state=args.ignore_state)
  File "/home/oerp/src/devops-tools/main.py", line 68, in _get_state
    "__state__.py file must be provided if --ignore-state flag "
exceptions.ArgumentsException: __state__.py file must be provided if --ignore-state flag is not used.

好吧,我可以做类似的事情:

self.assertTrue('ArgumentsException' in str(e.stderr))

但也许有更优雅的方式来检查我的异常?

标签: pythonpython-3.xexception-handling

解决方案


推荐阅读