簡體   English   中英

創建函數以處理Python中的異常

[英]Creating Function to handle exceptions in Python

我想知道是否有可能編寫一個函數來避免調用try ... except每次都會阻塞Python中有風險的函數。

我嘗試了以下代碼,但是沒有用:

def e(methodtoRun):
    try:
        methodtoRun.call()
    except Exception as inst:
        print(type(inst))    # the exception instance
        print(inst.args)     # arguments stored in .args
        print(inst)          # __str__ allows args to be printed directly,


def divider(a, b):
    return a / b

e(divider(1,0))

在這段代碼中,Python運行divider(1,0)並嘗試將結果作為參數傳遞給e函數。

我想要做的是將一個函數作為參數傳遞,並在try ... except塊中運行它,以便在發生任何錯誤時將錯誤直接添加到日志中。

這可能嗎?

您可以這樣做..但是它確實使代碼閱讀起來並不好。

您的示例不起作用,因為您將函數調用divider(1,0)的“結果”提供給e 因為您已經調用了該函數並且該異常已經發生,所以永遠不會處理該異常。

您需要將函數本身和任何參數傳遞給e

更改為:

def e(methodtoRun, *args):
    try:
        methodtoRun(*args)    # pass arguments along
    except Exception as inst:
        print(type(inst))    # the exception instance
        print(inst.args)     # arguments stored in .args
        print(inst)          # __str__ allows args to be printed directly,


def divider(a, b):
    return a / b

e(divider,1,0)    # give it the function and any params it needs

要得到:

<type 'exceptions.ZeroDivisionError'>
('integer division or modulo by zero',)
integer division or modulo by zero

在進行任何認真的代碼審查時,您都應該找回代碼來解決此問題。 我強烈建議不要這樣做-您僅捕獲最一般的異常,並且使此構造更加靈活將使它使用起來很恐怖!

例外應為:

  • 盡可能在本地處理
  • 盡可能具體

您的代碼正好相反。

Doku:

暫無
暫無

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

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