2010-12-01 58 views
14

我有一些處理異常的代碼,並且我只想在特定的異常情況下執行某些操作,而且只在調試模式下執行。因此,例如:在python中處理特定的異常類型

try: 
    stuff() 
except Exception as e: 
    if _debug and e is KeyboardInterrupt: 
     sys.exit() 
    logging.exception("Normal handling") 

因此,我不希望只是添加:

except KeyboardInterrupt: 
    sys.exit() 

,因爲我想保持這個調試代碼最小

+1

其實你問什麼? – Marii 2010-12-01 21:44:39

回答

18

那麼,真的,你可能應該保持KeyboardInterrupt處理程序分開。你爲什麼只想在調試模式下處理鍵盤中斷,但是否則吞下它們?

這就是說,你可以使用isinstance來檢查對象的類型:

try: 
    stuff() 
except Exception as e: 
    if _debug and isinstance(e, KeyboardInterrupt): 
     sys.exit() 
    logger.exception("Normal handling") 
19

這區別幾乎是完成它的方式。

try: 
    stuff() 
except KeyboardInterrupt: 
    if _debug: 
     sys.exit() 
    logging.exception("Normal handling") 
except Exception as e: 
    logging.exception("Normal handling") 

有最小的重複。不是零,但是,但最小。

如果「正常處理」不止一行代碼,您可以定義一個函數以避免重複這兩行代碼。

+0

你打我30秒,我認爲 – Velociraptors 2010-12-01 21:49:53

+0

它是「除了例外,e:」 – marcog 2010-12-01 21:52:53

+5

@marcog:`除了異常作爲e`在Python 2.6+中有效。 – mipadi 2010-12-01 21:54:34

0

try: 
    stuff() 
except KeyboardInterrupt: 
    if _debug: 
     logging.exception("Debug handling") 
     sys.exit() 
    else: 
     logging.exception("Normal handling") 
0

或者使用在其他的答案中提到的標準方法,或者,如果你真的想在考試除塊,那麼你可以使用isinstance()有什麼不對。

try: 
    stuff() 
except Exception as e: 
    if _debug and isinstance(e, KeyboardInterrupt): 
     sys.exit() 
    logging.exception("Normal handling") 
1

你應該讓一個KeyboardInterrupt泡沫一路上漲並捕獲它的最高水平。

if __name__ == '__main__': 
    try: 
     main() 
    except KeyboardInterrupt: 
     sys.exit() 
    except: 
     pass 

def main(): 
    try: 
     stuff() 
    except Exception as e: 
     logging.exception("Normal handling") 
     if _debug: 
      raise e 
0
try: 
    stuff() 
except KeyboardInterrupt: 
    if _debug: 
     sys.exit() 
    logging.exception("Normal handling") 
except ValueError: 
    if _debug: 
     sys.exit() 
    logging.exception("Value error Normal handling") 
else: 
    logging.info("One more message without exception") 
0

您可以在Python命名特定的例外:

try: 
    stuff() 
except KeyboardInterrupt: 
    sys.exit() 
except Exception: 
    normal_handling()