python停止异常传递

时间:2015-11-06 09:12:52

标签: python error-handling exception-handling

我有一个自定义InvalidError,我希望我的函数可以处理两种错误:一种是InvalidError,另一种是其他错误。我试着用这种方式:

try:
   a = someFunc()
   if a:
      # do things
   else:
      raise InvalidError('Invalid Error!')
except InvalidError as e:
      return "Invalid"
except Exception as ex:
      return "Other"

但似乎我会得到Other。如何以正确的方式实现我的功能?

2 个答案:

答案 0 :(得分:0)

您能告诉我们您是如何创建InvalidError类的吗?它正在发挥作用。

03:00.0 3D controller: NVIDIA Corporation GK110GL [Tesla K20c] (rev a1)
        Subsystem: NVIDIA Corporation Device 0982
        Flags: bus master, fast devsel, latency 0, IRQ 11
        Memory at f9000000 (32-bit, non-prefetchable)
        Memory at d0000000 (64-bit, prefetchable)
        Memory at ce000000 (64-bit, prefetchable)
        Capabilities: <access denied>
        Kernel driver in use: nvidia
        Kernel modules: nvidia_346, nouveau, nvidiafb
...
83:00.0 3D controller: NVIDIA Corporation GK110GL [Tesla K20c] (rev a1)
        Subsystem: NVIDIA Corporation Device 0982
        Flags: bus master, fast devsel, latency 0, IRQ 11
        Memory at cc000000 (32-bit, non-prefetchable)
        Memory at b0000000 (64-bit, prefetchable)
        Memory at ae000000 (64-bit, prefetchable)
        Capabilities: <access denied>
        Kernel driver in use: nvidia
        Kernel modules: nvidia_346, nouveau, nvidiafb

答案 1 :(得分:0)

这样做的一种方法是创建一个上下文管理器类。在竞赛管理器中,您可以忽略您喜欢的任何错误,

E.g。

class ctx_mgr:

def __enter__(self):
    cm = object()
    return cm    

def __exit__(self, exc_type, exc_value, exc_tb):
    return (exc_type == InvalidError)

def __enter__(self): cm = object() return cm def __exit__(self, exc_type, exc_value, exc_tb): return (exc_type == InvalidError)