2015-11-06 144 views
0

我有一個自定義InvalidError,我想我的函數處理兩種錯誤:一個是InvalidError,另一個是所有其他錯誤。我試着這樣說:python停止異常通過

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兩種方式。我如何以正確的方式實現我的功能?

+0

是否定義爲InvalidError擴展異常類的類? –

+0

[在Python中手動引發(拋出)異常]的可能重複(http://stackoverflow.com/questions/2052390/manually-raising-throwing-an-exception-in-python) – JasmineOT

回答

0

你能告訴我們你是如何創建InvalidError類的嗎?這是工作。

class InvalidError(Exception): 
    pass 

>>> try: 
... raise InvalidError("dsfsdf") 
... except InvalidError as my_exception: 
... print "yes" 
... except Exception as e: 
... print "No" 
... 
yes 
0

這樣做的一種方法是創建一個上下文管理器類。在競爭管理器中,您可以忽略任何您喜歡的錯誤,例如

例如,

class ctx_mgr:

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

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

with ctx_mgr: a = someFunc()