2014-02-15 12 views
0

我必須處理大量的try/except。我懷疑正確的做法。Python - Try/Except,什麼是好的,什麼是錯的?

選項1:

inst = Some(param1, param2) 
try: 
    is_valid = retry_func(partial(inst.some_other), max_retry=1) 
except RetryException, e: 
    SendMail.is_valid_problem(e) 

if is_valid: 
    print "continue to write your code" 
    ... 
    *** more code with try/except *** 
    ... 

選項2:

inst = Some(param1, param2) 
try: 
    is_valid = retry_func(partial(inst.some_other), max_retry=1) 
    if is_valid: 
     print "continue to write your code" 
     ... 
     *** more code with try/except *** 
     ... 
except RetryException, e: 
    SendMail.is_valid_problem(e) 

在選項1,甚至是引發異常, 「is_valid」 將受到考驗,我不需要這個。

在選項2中,我認爲是正確的,但代碼看起來像一個「回調地獄」。

我應該選擇什麼樣的選項什麼樣的選擇是正確的?

+0

選項1是要走的路 – thefourtheye

回答

7

保持異常處理儘可能接近引發異常的代碼。您不希望在代碼中意外掩蓋另一個問題,您認爲這不會引發相同的異常。

這裏有第三個選擇,使用else:套件try聲明:

inst = Some(param1, param2) 
try: 
    is_valid = retry_func(partial(inst.some_other), max_retry=1) 
except RetryException, e: 
    SendMail.is_valid_problem(e) 
else: 
    if is_valid: 
     print "continue to write your code" 
     ... 
     *** more code with try/except *** 
     ... 

如果沒有例外的try套件提出的else:套件時,纔會執行。

1

我認爲選項1更好。原因是你應該總是試一試,除了你期望拋出異常的代碼。增加代碼會增加捕獲不需要的異常的風險。

1

從你的條件,條件1是更好,你可以使用別的替代if is_valid

這裏有一些嘗試除外:

這裏是嘗試簡單的語法....除外。 ..else塊:

try: 
    You do your operations here; 
    ...................... 
    except ExceptionI: 
    If there is ExceptionI, then execute this block. 
    except ExceptionII: 
    If there is ExceptionII, then execute this block. 
    ...................... 
    else: 
    If there is no exception then execute this block. 

的除與多個異常子句:

try: 
    You do your operations here; 
    ...................... 
    except(Exception1[, Exception2[,...ExceptionN]]]): 
    If there is any exception from the given exception list, 
    then execute this block. 
    ...................... 
    else: 
    If there is no exception then execute this block. 

在try-finally語句:

try: 
    You do your operations here; 
    ...................... 
    Due to any exception, this may be skipped. 
    finally: 
    This would always be executed. 
0

確保如果發生錯誤,保持事業try語句裏面。這樣,它會捕獲錯誤並在除外部分對其進行分類。最後還有。如果嘗試不起作用,但「except」錯誤不起作用,它將執行「finally」聲明。如果最後沒有,程序會卡住。這與嘗試,除了一個示例代碼: 進口SYS 進口數學 而真: X = sys.stdin.readline() X =浮子(X) 嘗試: X = math.sqrt(X) y = int(x) 如果x!= y: print(「您的號碼不是平方號碼。「) ELIF X == Y: 打印(」 你的號碼是平方數 「) 除(ValueError異常): 打印(」 你的數字爲負「) ValueError異常是錯誤你得到的sqrt-ING一個負數