簡體   English   中英

簡化Python中的try-except塊

[英]Simplify try-except blocks in 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

由於每個模塊都使用類似的代碼來捕獲異常,是否有辦法將異常捕獲放入所有模塊都使用的共享文件中?

我不會這樣做,但是您可以在類似以下的模塊中創建一個函數:

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) ,並傳遞需要具有正確上下文的參數。

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

最簡單的方法是創建一個接受兩個參數的函數:另一個函數是您要“嘗試”的代碼,以及在發生異常的情況下要執行的“操作”。

然后:

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

然后,在導入新模塊之后,您可以使用如下功能:

myModuleFunction(divideByZero, 'printMe')

假設您有一個名為divideByZero()的函數;

我希望這有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM