2015-12-04 36 views
0

我有很多模塊。他們都有類似的嘗試,除了在每個文件塊,像這樣:簡化Python中的try-except塊

from shared.Exceptions import ArgException # and others, as needed 

try: 

    do_the_main_app_here() 

except ArgException as e: 

    Response.result = { 
     'status': 'error', 
     'message': str(e) 
    } 
    Response.exitcode('USAGE') 

# more blocks like the above 

與ArgException(和其他異常)被定義爲:

from abc import ABCMeta, abstractmethod 
class ETrait(Exception): 
    __metaclass__ = ABCMeta 
    @abstractmethod 
    def __init__(self, msg): 
     self.msg = msg 
    def __str__(self): 
     return self.msg 

class ArgException(ETrait): pass 

由於每個模塊都使用類似的代碼捕獲異常,有沒有辦法將異常捕捉到所有模塊使用的共享文件中?

回答

0

我不會那麼做的,但你可以像一個模塊中創建一個函數:

from shared.Exceptions import ArgException # and others, as needed 
def try_exec(execution_function) 
    try: 
     execution_function() 
    except ArgException as e: 
     Response.result = { 
      'status': 'error', 
      'message': str(e) 
     } 
     Response.exitcode('USAGE') 

,然後調用try_exec(do_the_main_app_here),每當你需要嘗試抓住你的指令塊,傳遞你需要有參數正確的上下文。

0

答案是肯定的,你可以創建一個模塊來做到這一點。

最簡單的方法是創建一個接受兩個參數的函數:帶有想要「嘗試」的代碼的另一個函數以及在發生異常時採取的「動作」。

然後:

def myModuleFunction(tryThisCode, doThis): 
    try: 
     returnValue = tryThisCode() 
     return returnValue 
    except ArgException as e: 
     if (doThis == "doThat"): 
      ... 
     else: 
      ... 

然後,導入新的模塊後,你可以用你的函數是這樣的:

myModuleFunction(divideByZero, 'printMe') 

假設你有一個名爲divideByZero()的函數;

我希望這會有所幫助。